我在使用scrollspy插件时遇到困难,以便在正确滚动时跟踪我的活动状态。我正在使用scrollspy.js库。我愿意优化插件,例如在某些偏移中发生状态变化。我无法在插件中找到任何选项来执行OffsetTop,因为我认为这样可以解决问题。下面是我的HTML结构和初始化插件的javascript。
<div class="faq_tabs hidden_faq_tabs">
<div id="my-nav">
<ul class="stickyMenu">
<li>
<a href="#general" data-spyer="general">General</a>
</li>
<li>
<a href="#student" data-spyer="student">Student</a>
</li>
<li>
<a href="#business" data-spyer="business">Business</a>
</li>
</ul>
</div>
</div>
<div>
<h1 id="general" class="spyon">GENERAL</h1>
</div>
<div>
<h1 id="student" class="spyon">STUDENT</h1>
</div>
<div>
<h1 id="business" class="spyon">BUSINESS</h1>
</div>
我已按如下所示自定义脚本以获取数据属性以添加活动类。
$('.spyon').scrollSpy();
$('.spyon').on('scrollSpy:enter', function(){
$('[data-spyer="' + $(this).attr('id') + '"]').addClass('spyedon');
});
$('.spyon').on('scrollSpy:exit', function(){
$('[data-spyer="' + $(this).attr('id') + '"]').removeClass('spyedon');
});
这是我使用插件的演示:
http://frakton.com/scholarbiz-v1.2/?id=22
在提供的链接中,您可以看到erorr。我愿意避免两个第一项的活跃状态。
答案 0 :(得分:1)
基本上我所要做的就是优化脚本并避免使用jquery scrollspy。下面是一个javascript代码,可能会帮助将来的某个人。
// Cache selectors
var lastId,
topMenu = $("#my-nav"),
topMenuHeight = topMenu.outerHeight(),
// All list items
menuItems = topMenu.find("a"),
// Anchors corresponding to menu items
scrollItems = menuItems.map(function() {
var item = $($(this).attr("href"));
if (item.length) {
return item;
}
});
// Bind click handler to menu items
// so we can get a fancy scroll animation
menuItems.click(function(e) {
var href = $(this).attr("href"),
o = href === "#" ? 0 : $(href).offset().top - topMenuHeight;
$('html, body').stop().animate({
scrollTop: o
}, 300);
e.preventDefault();
});
// Bind to scroll
$(window).scroll(function() {
// Get container scroll position
var fromTop = $(this).scrollTop() + topMenuHeight;
// Get id of current scroll item
var cur = scrollItems.map(function() {
if ($(this).offset().top < fromTop)
return this;
});
// Get the id of the current element
cur = cur[cur.length - 1];
var id = cur && cur.length ? cur[0].id : "";
if (lastId !== id) {
lastId = id;
// Set/remove active class
menuItems
.parent().removeClass("active")
.end().filter("[href=#" + id + "]").parent().addClass("active");
}
});
您需要做的就是更改与topMenu变量中可能具有的菜单或粘性导航相对应的类的值,并为活动类设置css的样式。