gpt4 book ai didi

jquery - 平滑链接滚动不是在整个主体上,而是在某些 div 上

转载 作者:行者123 更新时间:2023-12-01 04:45:58 26 4
gpt4 key购买 nike

我使用此代码来实现平滑的链接滚动:

    function filterPath(string) {
return string
.replace(/^\//,'')
.replace(/(index|default).[a-zA-Z]{3,4}$/,'')
.replace(/\/$/,'');
}

$('a[href*=#]').each(function() {
if ( filterPath(location.pathname) == filterPath(this.pathname)
&& location.hostname == this.hostname
&& this.hash.replace(/#/,'') ) {
var $targetId = $(this.hash), $targetAnchor = $('[name=' + this.hash.slice(1) +']');
var $target = $targetId.length ? $targetId : $targetAnchor.length ? $targetAnchor : false;
if ($target) {
$(this).click(function() {
var targetOffset = $target.offset().top;
$('html, body, .container-1-2').animate({
scrollTop: $target.offset().top - 70}, 600
);

return false;
});
}
}
});

我不是滚动整个页面,而是只滚动某些具有container-1-2类的div。

我遇到的问题是,当单击 anchor 链接时,它会滚动到指定的 id,但是当我再次单击同一链接时,它会滚动到顶部。只是不知道如何防止再次滚动到顶部并保持静止。

最佳答案

我找到了解决方案。

$(function() {
$('a[href*=#]').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('.content-container').animate({
scrollTop: $('.content-container').scrollTop() + target.offset().top - 70
}, 1000);
return false;
}
}
});
});

关于jquery - 平滑链接滚动不是在整个主体上,而是在某些 div 上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29791612/

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