当我访问my_site.com/page.php#something
时,滚动位置是携带此特定hashtag而非页面顶部的元素之一。如何在加载页面时禁用锚点跳转
执行window.scrollTo(0, 0);
不会改变这个事实。那么可以做什么?
编辑:也尝试从How to disable anchor "jump" when loading a page?接受答案。似乎没有工作了。
当我访问my_site.com/page.php#something
时,滚动位置是携带此特定hashtag而非页面顶部的元素之一。如何在加载页面时禁用锚点跳转
执行window.scrollTo(0, 0);
不会改变这个事实。那么可以做什么?
编辑:也尝试从How to disable anchor "jump" when loading a page?接受答案。似乎没有工作了。
有了这个HTML代码:
<a href="#test">link</a>
<div id="test"></div>
你能避免滚动div元素,而是通过使用此代码滚动至窗口的顶部:
$("a").on("click", function(e) {
e.preventDefault();
window.scrollTo(0, 0);
});
编辑:
您可以尝试添加以下内容:
var firstVisit = true;
$(window).scroll(function() {
if (firstVisit) {
window.scrollTo(0, 0);
firstVisit = false;
}
});
你需要做的是存储hashtag供以后使用,然后删除它,以便浏览器没有任何内容可以滚动到。
重要的是,不要将代码的那部分放在$()或$(window).load()函数中,因为它会迟到,并且浏览器已经移动到标记中。
// store the hash (DON'T put this code inside the $() function, it has to be executed
// right away before the browser can start scrolling!
var target = window.location.hash,
target = target.replace('#', '');
// delete hash so the page won't scroll to it
window.location.hash = "";
// now whenever you are ready do whatever you want
// (in this case I use jQuery to scroll to the tag after the page has loaded)
$(window).load(function() {
if (target) {
$('html, body').animate({
scrollTop: $("#" + target).offset().top
}, 700, 'swing', function() {});
}
});
我遇到了一个FF错误,我在一个非常长的列表中使用了max-height overflow-y,FF将向下滚动到隐藏节点将在dom中的位置。这只使用了实际代码的前三行(不是注释),并且这改正了我与FireFox的问题。 – wintercyborg 2016-08-24 18:44:37
谢谢,但问题不是当我点击任何东西,而是当我“访问”页面。 – drake035 2014-11-24 01:43:39
@ drake035我编辑了答案。不知道它是否是最有效的或最好的方式,但它似乎工作。 – Dim13i 2014-11-24 01:55:14
Thx但它不起作用。 – drake035 2014-11-24 11:03:38