开发者

Scroll to fragment identifier on new page at load w/ JQuery?

开发者 https://www.devze.com 2023-02-14 18:14 出处:网络
I\'m trying to see if its possible to have some simple HTML markup like so: <a href=\"www.mysite.com/pageXXX#location1\"></a>

I'm trying to see if its possible to have some simple HTML markup like so:

<a href="www.mysite.com/pageXXX#location1"></a>
<a href="www.mysite.com/page1#location1"></a>
<a href="www.mysite.com/page2#location1"></a>
<a href="www.mysite.com/page3#location1"></a>

...and then, have it scroll down to the ID #location1 when the new page loads with a simple JQuery script of some sort? Or if this is something that could be achieved with the scrollTo plugin, how might I go about that instead?

The catch is that the link exists on pageXXX, and the ID to be scrolled to is on ALL pages, ie. pageXXX, page1, page2, page3, etc......Ideally, if there's a开发者_Go百科lso a way to remove the hash mark and the identifier from the URL that would be great too, but at the moment just having it smoothly scroll down to the ID on the new page is all I'm after.


You could add a setTimeout so it waits a bit then scrolls down?

function goToByScroll(id){
        $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}
var hash = window.location.hash;

setTimeout(function(){
      goToByScroll(hash);
},2000);


An alternative:

Instead of

<a href="www.mysite.com/pageXXX#location1"></a>

Try

<a href="www.mysite.com/pageXXX?location1"></a>

You can get the hash to put into the link this way:

var nothash = window.location.search;
var hash = nothash.substring(1);

Reference: https://developer.mozilla.org/en/DOM/window.location

Here you prevent the page from jumbing anywhere and you can do the next steps (putting the hash in a animated scroll function) without worrying about, if it fires fast enough.

0

精彩评论

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