我用一些 java 脚本设置我的导航栏,告诉它在浏览器中一直向上滚动时添加类 .top-of-page,并且该类在导航栏上有透明背景。一旦我开始向下滚动,背景颜色就会出现在导航栏上。我想要实现的是有 0.3 秒左右的过渡,使导航栏上的背景淡入淡出。尝试了几种不同的方法,但无法弄清楚这一点,我对 java 脚本一点也不熟悉。
<script> $(window).on("scroll", function() {
var scrollPos = $(window).scrollTop();
if (scrollPos <= 0) {
$('.navbar-default').addClass('top-of-page');
} else {
$('.navbar-default').removeClass('top-of-page');
}
});
</script>
.navbar-default {
background:linear-gradient(#595959, black);
min-height: 80px;
position: fixed;
border-radius: 5px;
border: none;
width: 100%;
z-index: 1;
}
.top-of-page {
background: transparent;
transition: all 0.3s ease-in-out 0s;
}
最佳答案
不能设置渐变过渡,但是可以使用下面的解决方案:
$(window).on("scroll", function() {
var scrollPos = $(window).scrollTop();
if (scrollPos <= 0) {
$('.navbar-default').addClass('top-of-page');
} else {
$('.navbar-default').removeClass('top-of-page');
}
});
html, body {height:100%}
#id {height:120%}
.navbar-default {
background:linear-gradient(#595959, transparent) black;
min-height: 80px;
position: fixed; top:0;
border-radius: 5px;
border: none;
width: 100%;
z-index: 1;
transition: all 0.3s;
}
.top-of-page {
background: transparent;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navbar-default"></div>
<div id="id"></div>
另一种解决方案使用伪元素及其不透明度的过渡:
$(window).on("scroll", function() {
var scrollPos = $(window).scrollTop();
if (scrollPos <= 0) {
$('.navbar-default').addClass('top-of-page');
} else {
$('.navbar-default').removeClass('top-of-page');
}
});
html,
body {
height: 100%
}
#id {
height: 120%
}
.navbar-default {
min-height: 80px;
position: fixed;
top: 0;
border-radius: 5px;
border: none;
width: 100%;
z-index: 1;
}
.navbar-default:before {
content: '';
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
background: linear-gradient(#595959, black);
opacity: 1;
transition: opacity 0.3s;
}
.top-of-page:before {
opacity: 0
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="navbar-default"></div>
<div id="id"></div>
关于javascript - 如何过渡进出我的导航栏的背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48413462/