Am currently trying to add scroll spy to my WordPress one page layout with the following code but nothing happens when I scroll down the page.
我目前正在尝试使用以下代码将滚动间谍添加到我的WordPress页面布局中,但当我向下滚动页面时没有任何反应。
The only thing that code is doing,is to remove the active class for.
代码唯一要做的就是删除活动类。
(function( $ ){
$("nav ul li a").addClass("marker");
var navLinks = $('nav ul li a'),
navH = $('nav').height(),
section = $('section'),
documentEl = $(document);
documentEl.on('scroll', function() {
var currentScrollPos = documentEl.scrollTop();
section.each(function() {
var self = $(this);
if (self.offset().top < (currentScrollPos + navH ) && (currentScrollPos + navH) < (self.offset().top + self.outerHeight())) {
var targetClass = '.' +self.attr('class') + 'marker';
navLinks.removeClass('active');
$(targetClass).addClass('active');
}
});
});
})(jQuery);
I simply added a dark background to active class in order to see he menu item changing color when I scroll down each section.
我只是在活动类中添加了一个深色背景,以便在向下滚动每个部分时看到菜单项改变颜色。
.active{
background-color:#000;
}
How can I apply the scroll spy properly?
如何正确应用滚动间谍?
1 个解决方案
#1
0
Try to wrap your js in dom ready statement
尝试将你的js包装在dom ready语句中
jQuery(function(){
$("nav ul li a").addClass("marker");
var navLinks = $('nav ul li a'),
navH = $('nav').height(),
section = $('section'),
documentEl = $(document);
documentEl.on('scroll', function() {
var currentScrollPos = documentEl.scrollTop();
section.each(function() {
var self = $(this);
if (self.offset().top < (currentScrollPos + navH ) && (currentScrollPos + navH) < (self.offset().top + self.outerHeight())) {
var targetClass = '.' +self.attr('class') + 'marker';
navLinks.removeClass('active');
$(targetClass).addClass('active');
}
});
});
});
#1
0
Try to wrap your js in dom ready statement
尝试将你的js包装在dom ready语句中
jQuery(function(){
$("nav ul li a").addClass("marker");
var navLinks = $('nav ul li a'),
navH = $('nav').height(),
section = $('section'),
documentEl = $(document);
documentEl.on('scroll', function() {
var currentScrollPos = documentEl.scrollTop();
section.each(function() {
var self = $(this);
if (self.offset().top < (currentScrollPos + navH ) && (currentScrollPos + navH) < (self.offset().top + self.outerHeight())) {
var targetClass = '.' +self.attr('class') + 'marker';
navLinks.removeClass('active');
$(targetClass).addClass('active');
}
});
});
});