简体   繁体   English

使用jQuery基于浏览器滚动位置添加CSS类 - 寻找更模块化的方法

[英]Adding a CSS class based on browser scroll position with jQuery - looking for a more modular approach

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. 在我当前的网站 (uptrde.com)上,我将其设置为当您滚动到页面的某个部分时,与该部分对应的导航将亮起。 However, I feel that the way I am doing it with jQuery is difficult and not modular at all. 但是,我觉得我使用jQuery的方式很难,而且根本不是模块化的。 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>

Here's what I'd recommend. 这是我推荐的。 Loop through each of the sections on the page and get the rendered height. 遍历页面上的每个部分并获得渲染高度。 Add each of those heights to an array, and then loop through the array when you are adding the classes. 将每个高度添加到数组中,然后在添加类时循环遍历数组。 Something like this: 像这样的东西:

$(window).scroll(function(){
     var scroll = $(window).scrollTop();
     var section_height = new Array();
     var section_position = new Array();
    $('.main-container').children().each(function(){
        section_height.push($(this).height());
        section_position.push($(this).offset().top);
    });

    for(i=0; i<section_position.length; i++){
        if($(window).scrollTop() > section_position[i] - (section_height[i] / 4)){
            $('.mainNav li').not(':nth-child('+i+')').find('a').removeClass('selected');
            $('.mainNav li:nth-child('+i+') a').addClass('selected');
        } else {
            $('.mainNav li:nth-child('+i+') a').removeClass('selected');
        }
    }
});

I haven't tested this with your site, but I used the same code on another site earlier today, and it worked like a charm. 我没有在你的网站上测试过这个,但我今天早些时候在另一个网站上使用了相同的代码,它就像一个魅力。 You'll want to play with the calculation used in the if statement in the for loop. 您将要使用for循环中if语句中使用的计算。 I have it set to change to the next section when you're about 1/4 of the height away from it. 当你距离它的高度的1/4左右时,我将它设置为更改为下一部分。 In other words, I wanted it to change to the next nav element when you were "almost" to it in the scroll position. 换句话说,我希望它在滚动位置“几乎”到它时更改为下一个nav元素。 I didn't want to have to wait till it was all the way at the top of your screen before changing the highlighted nav element. 在更改突出显示的导航元素之前,我不想等到屏幕顶部一直都是这样。 You, however, may choose to do it differently. 但是,您可以选择以不同方式执行此操作。

maybe this can help you 也许这可以帮到你

$(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/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM