Load page directly to anchor tag

假如想象 提交于 2019-12-11 00:42:26

问题


When I load a page with a hash tag in the URL, the page loads and then jumps to the anchor tag. Is there any way to prevent this "jump", either by loading the page directly to the anchor tag or at least making the scrolling smooth?

I see this problem in Chrome and Firefox, but not IE.


回答1:


If you're still experiencing the jumping issue, you could something with jQuery:

//Use a RegEx pattern to search for an id, if present
var pattern = new RegExp('\#(.*)');
var id = pattern.exec(window.location)[0].replace('#','');
//Prevent the browser's default behavior of jumping to the id
document.location = '#';
//When the page finishes loading, smoothly scroll to the specified content
$(document).ready(function() {
    if(id != "") {
        $('html,body').animate({
            scrollTop: $('#' + id).offset().top,
        }, 650);
    }
});

Note that this will only work once per page load.



来源:https://stackoverflow.com/questions/21709638/load-page-directly-to-anchor-tag

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!