[英]Smooth scroll to anchor offset pixels, except one specific anchor?
我有一个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像素,这是我需要做的,除了一个锚点之外,是否可以添加一行代码,写上“ X类除外”之类的东西? jQuery新手在这里;)
任何帮助将是巨大的,谢谢。
在click事件中,您既可以访问单击的nav元素(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,则可以将data属性放在<a>或目标元素上,例如
<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)
如果要完全排除某个锚,可以将其从锚选择器中删除。 代替这个
$('a[href^="#"]')
像这样只排除某个锚点:
$('a[href^="#"]:not([href="#somethingBad"])')
或排除具有特定类别的所有锚点,例如:
$('a[href^="#"]:not(.excludeMe)')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.