使用jQuery基于浏览器滚动位置添加CSS类 - 寻找更加模块化的方法 [英] Adding a CSS class based on browser scroll position with jQuery - looking for a more modular approach
问题描述
在我目前的网站(uptrde.com)上,我设置为当您滚动到页面的某个部分时与该部分对应的导航a点亮。然而,我觉得我用jQuery做的方式是困难的,而不是模块化的。我的代码为动画页面滚动工作正常,只是这最后一点是给我麻烦。我想让这个代码更模块化,所以如果我在未来添加更多的部分到网站,我不必找出新的价值观。谢谢您的帮助。
On my current site(uptrde.com) I have it setup to when you scroll to a certain section of the page the nav a that corresponds with that section lights up. However, I feel that the way I am doing it with jQuery is difficult and not modular at all. My code for animating the page scrolls works fine, just this last bit is giving me trouble. I would like to make this code more modular so if I add more sections to the site in the future I don't have to figure out new values. Thank you for your help.
$(window).scroll(function() {
$(".mainNav a").removeClass("selected");
var scroll = $(window).scrollTop();
//add the 'selected' class to the correct id element based on the scroll amount
if (scroll >= 0 && scroll <= 855) {
$("#homeNav").addClass("selected");
} else if (scroll >= 855 && scroll <= 1808) {
$("#aboutNav").addClass("selected");
} else if (scroll >= 1808 && scroll <= 2700) {
$("#sampleNav").addClass("selected");
} else if (scroll >= 2700 && scroll <= 3780){
$("#clientsNav").addClass("selected");
} else {
$("#contactNav").addClass("selected");
}
});
<nav id="menu">
<ul class="mainNav">
<li><a href="#top" id="homeNav" class="selected">Home</a></li>
<li><a href="#about-header" id="aboutNav">About Us</a></li>
<li><a href="#samples-header" id="sampleNav">Samples</a></li>
<li><a href="#clients-header" id="clientsNav">Clients</a></li>
<li><a href="#contact-header" id="contactNav">Contact</a></li>
</ul>
</nav>
推荐答案
也许这可以帮助你
$(function() {
$(window).scroll(function() {
var scroll = $(window).scrollTop() + 90;
var currentArea = $('.area').filter(function() {
return scroll <= $(this).offset().top + $(this).height();
});
$('nav a').removeClass('selected');
$('nav a[href=#' + currentArea.attr('id') +']').addClass('selected');
//console.debug('nav a[href=#' + currentArea.attr('id') +']');
});
});
JSFiddle: http://jsfiddle.net/LGzxq/1/
JSFiddle: http://jsfiddle.net/LGzxq/1/
这篇关于使用jQuery基于浏览器滚动位置添加CSS类 - 寻找更加模块化的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!