开发者

Prevent default hash behavior on page load

I have a page with a tabbed interface. Each tab has a unique id. I've enabled links pointing to that page with the appended id after the hash, and I'm now trying to circumvent the default browser behavior that opens a URL with hash at the location of the element on the page.

So:

  • pageA links to pageB like this: <a href="pageB.php#Tab4">Go</a>
  • pageB opens, and my jQuery activates the correct tab, but the browser has scrolled do开发者_高级运维wn to where <div id="Tab4"> is located on the page.

That's exactly what I want to prevent.

Any ideas? Thanks!


There isn't a way to prevent the default hash behavior, but you can alter your hash scheme so the #tag doesn't correspond to any ID on your page. On page load, take the hash value and append a constant (ex: _hash), then scroll to that using jQuery.

Example: http://mysite/page.php#tab4

page.php has <div id="tab4_hash"></div>

On page load, get the div by doing tab4 + _hash


I would use this:

window.scrollTo(0,0);

This way you don't need to change element id's or anything else.

I came across the problem where I wanted to scroll down to the tab, but for some reason it scrolled past it to the bottom of the page (no, there was not a duplicate id). I think it is because the browser would scroll to the id before the content finished loading, and the extra content pushed the element above the new scroll position). I fixed it with this:

if(document.location.hash)
{
    window.location = document.location.hash;
}

the "if" statement here is mandatory or you might get an infinite loop


After you're done loading the right tab, run this:

window.location = '#';


  1. You should just hide the element with id=hash by default
  2. Аnd then, after the page loads, you make the element visible.

You can find more info here: How to disable anchor "jump" when loading a page?

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜