Oll*_*y F 6 html javascript css jquery
我有一个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);
});
});
});
Run Code Online (Sandbox Code Playgroud)
它变成-59像素,这是除了一个锚之外我需要它做的事情,有没有办法我可以添加一行代码'除了类X'之外的东西?Jquery新手在这里;)
任何帮助都会很棒,谢谢.
小智 2
在单击事件中,您可以访问单击的导航元素 (this) 和滚动到的目标 ($target)。您可以查看其中任何一个来确定您需要抵消 -59 以外的某个金额。
如果您需要有不同偏移量的情况很少,您可以这样做:
var offset = -59;
if ($(this).attr(href)=="#something") offset=-100; //or whatever special offset you need
Run Code Online (Sandbox Code Playgroud)
并更改这一行:
'scrollTop': $target.offset().top-59
Run Code Online (Sandbox Code Playgroud)
对此:
'scrollTop': $target.offset().top+offset
Run Code Online (Sandbox Code Playgroud)
如果您想要一个更通用的解决方案并且可以访问 html,您可以在 <a> 或目标元素上放置一个 data 属性,例如
<a href="#something" data-scroll-offset=-100></a>
Run Code Online (Sandbox Code Playgroud)
然后,与第一种方法类似:
var offset=-59;
if ($(this).attr("data-scroll-offset")!==null) offset=$(this).attr("data-scroll-offset");
Run Code Online (Sandbox Code Playgroud)
如果它在目标元素上,它将是 $target 而不是 $(this)
如果您想完全排除某个锚点,可以将其从锚点选择器中删除。而不是这个
$('a[href^="#"]')
Run Code Online (Sandbox Code Playgroud)
仅排除某个锚点,如下所示:
$('a[href^="#"]:not([href="#somethingBad"])')
Run Code Online (Sandbox Code Playgroud)
或排除具有特定类别的任何锚点,如下所示:
$('a[href^="#"]:not(.excludeMe)')
Run Code Online (Sandbox Code Playgroud)