[英]Change header background colour when page scrolls
我一直在寻找解决方案,但我无法让它工作。
当用户开始滚动页面时,我希望我的页眉从透明背景变为白色背景。
HTML代码是:
<div class="header">
<div class="topbar"></div>
<div class="sitelogo"></div>
<nav id="navigation">
<ul>
<li id="twitter"><a href="http://www.twitter.com/iamdanmorris"><em>Twitter</em></a></li>
<li><a href="#contact">Contact</a></li>
<li><a href="#blog">Blog</a></li>
<li><a href="#">Portfolio</a></li>
<li><a href="#">About</a></li>
<li><a href="#">Home</a></li>
</ul>
</nav>
<div style="clear:both;"></div>
</div>
CSS代码是:
.header {
position: fixed;
top: 0;
left: 0;
width: 100%;
padding: 0;
z-index: 10000;
-webkit-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);
-moz-box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);
box-shadow: 0 1px 5px rgba(0, 0, 0, 0.25);
transition: all 0.2s ease-in-out;
height: auto;
background-color:transparent;
}
$(window).on("scroll", function() {
if($(window).scrollTop() > 50) {
$(".header").addClass("active");
} else {
//remove the background property so it comes transparent again (defined in your css)
$(".header").removeClass("active");
}
});
小提琴: http : //jsfiddle.net/634d6vgq/2/
如果用户从顶部滚动超过 50 个像素,这将添加background-color: #fff
到元素
这将添加一个“活动”类,以便您可以在 css 中对其进行样式设置(更易于维护)
编辑:
$(function() {
$(window).on("scroll", function() {
if($(window).scrollTop() > 50) {
$(".header").addClass("active");
} else {
//remove the background property so it comes transparent again (defined in your css)
$(".header").removeClass("active");
}
});
});
还有你的 css:
.active { background-color: #fff}
确保你也添加了这个css规则,否则背景颜色不会改变
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.