CSS 在滚动时设置 Bootstrap 导航栏透明度
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29646622/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set Bootstrap navbar transparency on scroll
提问by Hiperkie
I use a secondary fille called custom.css to overwrite the bootstrap code and I would like to know how to create a code that is activating only when the visitor of my site is not in the very top of the page.
我使用一个名为 custom.css 的辅助文件来覆盖引导程序代码,我想知道如何创建一个仅在我网站的访问者不在页面顶部时才激活的代码。
Until now I created a transparent navbar using the default code provided by bootstrap. The only thing I have to do is to set it to execute: background-color: #color
when the visitor is scrolling down.
到目前为止,我使用 bootstrap 提供的默认代码创建了一个透明的导航栏。我唯一要做的就是将它设置为执行:background-color: #color
当访问者向下滚动时。
Example: https://www.lyft.com/
示例:https: //www.lyft.com/
When I am in the top of the page, the navbar is transparent, but when I scroll down it becomes opaque.
当我在页面顶部时,导航栏是透明的,但是当我向下滚动时,它变得不透明。
回答by David Passmore
Ok you need the following code to achieve this effect: (I am going to use jQuery as it is the bootstrap supported language).
好的,您需要以下代码来实现此效果:(我将使用 jQuery,因为它是引导程序支持的语言)。
jQuery:
jQuery:
/**
* Listen to scroll to change header opacity class
*/
function checkScroll(){
var startY = $('.navbar').height() * 2; //The point where the navbar changes in px
if($(window).scrollTop() > startY){
$('.navbar').addClass("scrolled");
}else{
$('.navbar').removeClass("scrolled");
}
}
if($('.navbar').length > 0){
$(window).on("scroll load resize", function(){
checkScroll();
});
}
You can also use ScrollSpy
to do this.
您也可以使用它ScrollSpy
来执行此操作。
and your CSS (example):
和您的 CSS(示例):
/* Add the below transitions to allow a smooth color change similar to lyft */
.navbar {
-webkit-transition: all 0.6s ease-out;
-moz-transition: all 0.6s ease-out;
-o-transition: all 0.6s ease-out;
-ms-transition: all 0.6s ease-out;
transition: all 0.6s ease-out;
}
.navbar.scrolled {
background: rgb(68, 68, 68); /* IE */
background: rgba(0, 0, 0, 0.78); /* NON-IE */
}
回答by saad
$(document).ready(function() {
$(window).scroll(function() {
if($(this).scrollTop() > height) {
$('.navbar').addClass('scrolled');
} else {
$('.navbar').removeClass('scrolled');
}
});
});