当我加载 URL 中带有哈希标记的页面时,页面会加载,然后跳转到锚标记。有没有什么方法可以防止这种“跳转”,要么直接将页面加载到锚标记,要么至少使滚动平滑?
我在 Chrome 和 Firefox 中看到这个问题,但在 IE 中没有。
如果你仍然遇到跳跃问题,你可以使用 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);
}
});
请注意,这只会在每次页面加载时起作用一次。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)