Change ul style when arriving to div(scrolling)

后端 未结 6 1495
-上瘾入骨i
-上瘾入骨i 2020-12-18 17:24

I would like to change a ul style on scrolling and arrive to div using jQuery, explanation down.

CSS:

#menu {
    background-color:#ccc;
    position         


        
6条回答
  •  一生所求
    2020-12-18 18:15

    This should do what you're asking, using only jQuery:

    $(document).scroll(function(e) {
        var detectrange = 50; //how close to the top of the screen does it need to get
        var scrolltop = $(window).scrollTop() + detectrange;
        $('.alldivs').each(function(i, el){
            if (scrolltop > $(el).offset().top) {
                $('.'+el.id).removeClass('menutext').addClass('menutext2');
            }
        });
    });
    

    Note that to make it work I had to apply the alldivs class on your div1, div2, div3, etc. and give the menu items classes corresponding to their IDs.

    Demo in this jsFiddle: http://jsfiddle.net/ss7YF/

    EDIT If you want only the closest one to be highlighted (for a fixed menu I'm guessing?) use this:

    $(document).scroll(function(e) {
        var scrolltop = $(window).scrollTop();
        var mindist = 1000;
        var closest = '';
        $('.alldivs').each(function(i, el){
            var thisdist = Math.abs(scrolltop - $(el).offset().top);
            if (thisdist < mindist) {
                closest = el.id;
                mindist = thisdist;
            }
        });
        if (closest != '') {
            $('.menutext2').toggleClass('menutext menutext2');
            $('.'+closest).toggleClass('menutext menutext2');
        }
    });
    

    jsFiddle: http://jsfiddle.net/ss7YF/1/

提交回复
热议问题