Change navigation font color based on background

后端 未结 5 1683
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-22 19:12

My problem is this. I have a fixed left navigation bar and I have to change the list font color based on the background of the section under it. The code is like this fiddle. So

5条回答
  •  长情又很酷
    2021-01-22 19:32

    Something like this would work:

    $(window).scroll(function() {
    
        /* get current scroll-position within window */
        var scroll = $(window).scrollTop();
    
        $('.mainLeft li').each(function() {
    
            /* get position of navigation-element (distance from top minus half of it's height, so that it changes color while it's half over black and half over white background) */
            var elementPositionTop = parseFloat($(this).offset().top) + (parseFloat($(this).height() / 2));
    
            /* change color for each background-change */
            if (elementPositionTop >= 320 && elementPositionTop <= 640 || elementPositionTop >= 960 && elementPositionTop <= 1280) {
                $(this).addClass('whiteText');
            } else {
                $(this).removeClass('whiteText');
            }
        });
    });
    

    Here's the additional CSS:

    .mainLeft li.whiteText a {
        color: #fff;
    }
    .section {
        height: 18px;
        overflow: hidden;
    }
    

    I gave the .section divs a fixed height because the JS I used works with fixed pixel values, and not all browsers interpret the height of elements the same if they're not defined...

    Here's a fiddle: http://jsfiddle.net/Niffler/z34cG/

提交回复
热议问题