jQuery 页面滚动时更改标题背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28266651/
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
Change header background colour when page scrolls
提问by iamdanmorris
I've been looking at a solution for this but I cannot get it to work.
我一直在寻找解决方案,但我无法让它工作。
I would like my page header to change from a transparent background to a white background as the user begins scrolling the page.
当用户开始滚动页面时,我希望我的页眉从透明背景变为白色背景。
HTML code is:
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 code is:
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;
}
回答by fdsugfh
$(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");
}
});
fiddle: http://jsfiddle.net/634d6vgq/2/
小提琴:http: //jsfiddle.net/634d6vgq/2/
This will add the background-color: #fff
to the element if user has scrolled more than 50 pixels from the top
background-color: #fff
如果用户从顶部滚动超过 50 个像素,这将添加到元素
This will add a class "active" so you can style it within the css (easier to maintain)
这将添加一个“活动”类,以便您可以在 css 中对其进行样式设置(更易于维护)
edit:
编辑:
$(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");
}
});
});
And your css:
还有你的 css:
.active { background-color: #fff}
Make sure you also add this css rule, orherwise the background color will not change
确保你也添加了这个css规则,否则背景颜色不会改变