admin管理员组

文章数量:1334666

If a user requests the following address (from another page), I want to scroll down to the contact form area:

.html#contact

How would I check if the URL contains the hash #contact?

If a user requests the following address (from another page), I want to scroll down to the contact form area:

http://www.example./index.html#contact

How would I check if the URL contains the hash #contact?

Share Improve this question asked Aug 12, 2014 at 12:10 Fellow StrangerFellow Stranger 34.1k37 gold badges178 silver badges250 bronze badges 4
  • what did you tried so far? – Bhushan Kawadkar Commented Aug 12, 2014 at 12:12
  • 1 possible duplicate of How can I check if one string contains another substring in JavaScript? – MarioDS Commented Aug 12, 2014 at 12:12
  • And perhaps even more specific dupe: stackoverflow./q/280634/1313143 – MarioDS Commented Aug 12, 2014 at 12:13
  • Haha you guys above are funny. The two first answers are so beautiful. And no, there is no better question/answer on SO that covers this as succintly. – Fellow Stranger Commented Aug 12, 2014 at 12:18
Add a ment  | 

5 Answers 5

Reset to default 4

Don't. The browser does that for you. Simply have a name="contact" attribute and the browser will scroll down to that element automatically. for instance:

<h2 name="contact">The contact form is below</h2>
<form> ...

You can use this simple code to get the URL hash.

var hash = window.location.hash;
if(hash == "#contact") {
    // code
}

Note: this will also return the "#" tag!

url.match(/#contact$/) should return the matches as an array. Just check if it's not null.

The hash in the URL will map to the node with the same ID value. So in your case the page will auto scroll to div with an idea of #contact

you can use

var urlName = document.location.href;
var hash = urlName.split("#").length;

本文标签: javascriptCheck URL if it has a specific anchor tagStack Overflow