gpt4 book ai didi

javascript - 使用 anchor 标记的 div 上的 Jquery Scroll 无法正常工作

转载 作者:行者123 更新时间:2023-11-28 14:46:23 24 4
gpt4 key购买 nike

我添加了一个 jQuery 代码,使用 anchor 标记在不同的 div 上滚动,滚动有效,但当它到达目标 div 时,它会滚动回页面顶部。这是我写的代码

$('a[href^="#"]').click(function(e) {
e.preventDefault();
var target = this.hash;
var $target = $(target);
$('html, body').animate({
'scrollTop': $target.offset().top - 160
}, 1000).stop();
});

有什么建议吗?

最佳答案

你可以这样做:

$(document).ready(function(){
$("a").on('click', function(event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
window.location.hash = hash;
});
}
});
});

关于javascript - 使用 anchor 标记的 div 上的 Jquery Scroll 无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52266918/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com