简体   繁体   中英

Javascript on scroll to change nav bar opacity is making my nav content dissapear

I've looked everywhere but I can't find an answer that applies to this problem.

I have a sticky nav bar that becomes opaque upon scrolling, using this code:

    var target = $('#navbar-container');
var targetHeight = target.outerHeight();

$(document).scroll(function(e){
    var scrollPercent = (targetHeight - window.scrollY) / targetHeight;
    if(scrollPercent >= 0){
        target.css('opacity', 1);
    }
    else  target.css('opacity', 0.50);
});

But this code makes the background, and everything within the nav bar opaque, and I want the text links, and a logo to remain visible. I've read about using an RGB background to make only the background opaque, but I'm unsure how to do this within this code's parameters. I'm sure there's a simple solution, but I can't find it!

Use the background-color attribute instead of opacity.

target.css('background-color', 'rgba(0, 0, 0, 0.5)');

rgba(red, green, blue, alpha)

This is because the parent container will affect any children when using opacity.

Use rgba .

CSS

#navbar-container {
    background-color: rgba(255, 255, 255, 1);
}

JS

var target = $('#navbar-container');
var targetHeight = target.outerHeight();

$(document).scroll(function(e){
    var scrollPercent = (targetHeight - window.scrollY) / targetHeight;
    if(scrollPercent >= 0){
        target.css('background-color', 'rgba(255, 255, 255, 1)');
    }
    else  target.css('background-color', 'rgba(255, 255, 255, 0.5)');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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