Change navigation font color based on background

后端 未结 5 1747
佛祖请我去吃肉
佛祖请我去吃肉 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:33

    To do what you asked for you can do this with jquery:

    working fiddle

    var _li, _sections;
    
    $(function() {
       _li = $("#mymenu").find("li"); 
        _sections =  $("#wrapper").find(".section");   
        $(window).on('scroll', liBgs);
    });
    
    
    function liBgs() {
        for (var i = 0; i < _li.length ; i++) {
            var _litop = _li.eq(i).offset().top; 
            for (var j = 0; j < _sections.length; j++) {
                var $s = _sections.eq(j),
                _sectop = $s.offset().top,
                _secbottom = $s.offset().top+$s.height()-20;
                if (_litop > _sectop && _litop > _secbottom) {
                    var _color = rgb2hex($s.css('background-color'));
                    _li.eq(i).find('a').css('color',  (_color=="#ffffff") ? "#000000" : "#ffffff");
                }             
            }
        }
    }
    
    function rgb2hex(rgb) {
        rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
        function hex(x) {
            return ("0" + parseInt(x).toString(16)).slice(-2);
        }
        return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
    }
    

    NOTE: rgb2hex() function was taken from this question: How to get hex color value rather than RGB value?

    What this code does:

    I'm basically comparing positions of the menu li's to the sections, checking under what section each li is over everytime you scroll.. I'm not sure this is very efficient, but for something small scale it's ok.. if anyone knows how to make this even more efficient I'll be happy to learn.

提交回复
热议问题