我有一个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新手在这里;)
任何帮助都会很棒,谢谢。
答案 0 :(得分:2)
On your click event, you have access to both the nav element you clicked on (this) and the target you are scrolling to ($target). You can look at either of those to determine that you need to offset by some amount other than -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
<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)
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)')