gpt4 book ai didi

javascript - 平滑滚动到 anchor 偏移像素,除了一个特定的 anchor ?

转载 作者:太空狗 更新时间:2023-10-29 15:13:50 26 4
gpt4 key购买 nike

我有一个 UL 导航,我有这个平滑滚动的 jQuery 工作:

$(document).ready(function () {
$(document).on("scroll", onScroll);

//smoothscroll
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");

$('a').each(function () {
$('.nav').removeClass('active');
})
$('.nav').addClass('active');

var target = this.hash,
menu = target;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top-59
}, 500, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});

它变为 -59 像素,这是我需要它为除一个 anchor 以外的所有 anchor 执行的操作,有没有办法可以添加一行代码来表示“X 类除外”或其他内容?这里是 Jquery 新手 ;)

任何帮助都会很棒,谢谢。

最佳答案

在您的点击事件中,您可以访问您点击的导航元素 (this) 和您滚动到的目标 ($target)。您可以查看其中任何一个以确定您需要抵消 -59 以外的某个数量。

如果需要不同偏移量的情况很少,您可以这样做:

var offset = -59;
if ($(this).attr(href)=="#something") offset=-100; //or whatever special offset you need

并更改这一行:

'scrollTop': $target.offset().top-59

为此:

'scrollTop': $target.offset().top+offset

如果你想要一个更通用的解决方案并且可以访问 html,你可以在 或目标元素上放置一个数据属性,比如

<a href="#something" data-scroll-offset=-100></a>

然后,类似于第一种方法:

var offset=-59;
if ($(this).attr("data-scroll-offset")!==null) offset=$(this).attr("data-scroll-offset");

如果它在目标元素上,它将是 $target 而不是 $(this)


如果您想完全排除某个 anchor ,您可以将其从 anchor 选择器中删除。而不是这个

$('a[href^="#"]')

像这样只排除某个 anchor :

$('a[href^="#"]:not([href="#somethingBad"])')

或像这样排除具有特定类别的任何 anchor :

$('a[href^="#"]:not(.excludeMe)')

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