开发者

How can I detect with javascript if an attribute "#" is appended to an url?

How can I detect with javascript if an attribute "#" is appended to an url ?

I need a cross-browser solution. I'm currently using the following code, but it works only in F开发者_JAVA技巧irefox:

if ((window.location.hash) || (window.location.hash != "#"))
    window.scrollBy(0,-60);

thanks


First, there seems to be an error in your posted code. If you're going for the common string is neither null nor empty nor '#' pattern, it should be:

if (window.location.hash && window.location.hash != "#")
    window.scrollBy(0,-60);

That said, since Location.hash is well-supported, the code above should work on all modern browsers.


The following line should do the job for you:

if(!!window.location.hash) // if 'true' you have an appending hash
     window.scrollBy(0,-60);

According to w3schools location.hash should work in all major browsers.


If you're finding that the hash property doesn't work in a key browser, you could always just do string parsing, a naive implementation might look like:

var url = window.location.href;
var hashLoc = url.lastIndexOf('#');
if(hashLoc > -1 && hashLoc < url.length )
     window.scrollBy(0,-60);


For good cross-browser support you can turn to jQuery. It might be overkill for your project, but overall it makes js developing much easier. There is an excellent hashchange plugin which I have used with great success for a couple of months.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜