[英]Smooth scroll to anchor offset pixels, except one specific anchor?
I have a UL nav, I've got this smooth scroll jQuery working: 我有一个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);
});
});
});
it goes to -59 pixels, which is what I need it to do for all but one anchor, is there a way I can add a line of code that says 'except class X' or something? 它达到了-59像素,这是我需要做的,除了一个锚点之外,是否可以添加一行代码,写上“ X类除外”之类的东西? Jquery novice here ;)
jQuery新手在这里;)
Any help would be great, thanks. 任何帮助将是巨大的,谢谢。
On your click event, you have access to both the nav element you clicked on (this) and the target you are scrolling to ($target). 在click事件中,您既可以访问单击的nav元素(this),也可以访问要滚动到的目标($ target)。 You can look at either of those to determine that you need to offset by some amount other than -59.
您可以查看其中任意一个以确定是否需要抵消-59以外的某个数量。
If you have very few cases you need to have a different offset for, you can do this: 如果情况很少,则需要使用其他偏移量,可以执行以下操作:
var offset = -59;
if ($(this).attr(href)=="#something") offset=-100; //or whatever special offset you need
And change this line: 并更改此行:
'scrollTop': $target.offset().top-59
to this: 对此:
'scrollTop': $target.offset().top+offset
If you want a more versatile solution and have access to the html, you can put a data attribute on either the < a> or the target element, like 如果您想要更通用的解决方案并可以访问html,则可以将data属性放在<a>或目标元素上,例如
<a href="#something" data-scroll-offset=-100></a>
And then, similarly to the first method: 然后,类似于第一种方法:
var offset=-59;
if ($(this).attr("data-scroll-offset")!==null) offset=$(this).attr("data-scroll-offset");
If it were on the target element, it would be $target instead of $(this) 如果在目标元素上,它将是$ target而不是$(this)
If you want to exclude a certain anchor entirely, you could remove it from the anchor selector. 如果要完全排除某个锚,可以将其从锚选择器中删除。 Instead of this
代替这个
$('a[href^="#"]')
Exclude only a certain anchor like so: 像这样只排除某个锚点:
$('a[href^="#"]:not([href="#somethingBad"])')
or exclude any anchors with a certain class like so: 或排除具有特定类别的所有锚点,例如:
$('a[href^="#"]:not(.excludeMe)')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.