Jquery 如何在加载页面时禁用锚点跳转
当我访问Jquery 如何在加载页面时禁用锚点跳转,jquery,scroll,hashtag,Jquery,Scroll,Hashtag,当我访问my_site.com/page.php#something时,滚动位置是携带此特定标签的元素之一,而不是页面顶部 执行window.scrollTo(0,0)不会改变这一事实。那么你能做什么呢 编辑:也尝试接受来自的答案。似乎不再有效。使用以下HTML代码: <a href="#test">link</a> <div id="test"></div> 编辑: 您可以尝试添加以下内容: var firstVisit = true; $(w
my_site.com/page.php#something
时,滚动位置是携带此特定标签的元素之一,而不是页面顶部
执行window.scrollTo(0,0)代码>不会改变这一事实。那么你能做什么呢
编辑:也尝试接受来自的答案。似乎不再有效。使用以下HTML代码:
<a href="#test">link</a>
<div id="test"></div>
编辑:
您可以尝试添加以下内容:
var firstVisit = true;
$(window).scroll(function() {
if (firstVisit) {
window.scrollTo(0, 0);
firstVisit = false;
}
});
您需要做的是存储标签供以后使用,然后删除它,这样浏览器就不会有任何可滚动的内容
重要的是,不要将该部分代码放在$()或$(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 () {});
}
});
谢谢,但问题不是当我点击任何东西时,而是当我“访问”页面时。@drake035我编辑了答案。不知道这是最有效的还是最好的方法,但它似乎有效。只是编辑了答案,因为滚动函数中的if条件有一个输入错误。如果可以,请再试一次。我在FF中遇到了一个错误,我在一个有很长列表的div上使用了max-height overflow-y,FF将向下滚动dom中隐藏节点的位置。这只使用了实际代码的前三行(不是注释),这纠正了我在FireFox上的问题
// 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 () {});
}
});