简体   繁体   中英

anchor links referring to the page sections not working on browser refresh, back and forward

I have made a html page with links inside the page.

<div>
<a href="#first">first</a>
<a href="#second">second</a>
<div id="first">First div</div>
<div id="second">Second div</div>
</div>

But this code doesn't work on page refresh and browser back and forward buttons. Does anyone know how to solve this problem. I am not looking for history api of html5 and history plugin of jquery. Want to create this in its basic format.

Ok I have found out how to do it after a lot of attempts. Right now this handles my purpose so I am going ahead with this solution.

$(window).on('hashchange', function () 
{
    var top = $(window.location.hash).offset().top;
    $(window).scrollTop(top);
});

This works for forward and back buttons. And for refresh also we need to do the same thing. Get the element from the hash and scroll to that element manually.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM