Changing sticky nav color based on div below's color

前端 未结 2 1098
萌比男神i
萌比男神i 2021-01-13 16:51

Basically on my site I have a sticky nav that has a transparent background. Below that I have light or dark colored content divs.

What I\'m trying to achieve is as y

相关标签:
2条回答
  • 2021-01-13 17:29

    Fiddle working:

    http://jsfiddle.net/bbazcyc8/1/

    var stickyOffset = $("#sticky").offset();
    var $contentDivs = $(".content");
    $(document).scroll(function() {
        $contentDivs.each(function(k) {
            var _thisOffset = $(this).offset();
            var _actPosition = _thisOffset.top - $(window).scrollTop();
            if (_actPosition < stickyOffset.top && _actPosition + $(this).height() > 0) {
                $("#current").html("Current div under sticky is: " + $(this).attr("class"));
                $("#sticky").removeClass("light dark").addClass($(this).hasClass("light") ? "light" : "dark");
                return false;
            }
        });
    });
    
    <div>
        <div id="sticky">Menu <span id="current"></span></div>
        <div class="content light"></div>
        <div class="content dark"></div>
        <div class="content light"></div>
        <div class="content dark"></div>
        <div class="content light"></div>
    </div>
    
    0 讨论(0)
  • 2021-01-13 17:33

    kabooya, everyone. I found this for you: http://jsfiddle.net/Niffler/z34cG/

    Try adding this

    $(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');
            }
        });
    });
    
    0 讨论(0)
提交回复
热议问题