javascript 在滚动时更改 div 的背景颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32675604/
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
Changing background color of div on scroll
提问by user2252219
BG color should be #1A1A1A on start then change after scrolling 210 px. Not sure where I'm going wrong.
BG 颜色在开始时应为 #1A1A1A,然后在滚动 210 像素后更改。不知道我哪里出错了。
$(document).ready(function(){
var scroll_pos = 0;
$(document).scroll(function() {
scroll_pos = $(this).scrollTop();
if(scroll_pos > 210) {
$("#left-panel").css('background-color', '#1A1A1A');
} else {
$("#left-panel").css('background-color', 'red');
}
});
});
采纳答案by Maximillian Laumeister
You need to bind your scroll event to your div
with id="left-panel"
, because that's the element that has the scrollbar on it (i.e. the element with overflow: auto
and a child element larger than itself).
你需要将你的滚动事件绑定到你的div
with id="left-panel"
,因为那是带有滚动条的元素(即元素 withoverflow: auto
和一个比自身大的子元素)。
Binding to document
or window
won't work, because in this case they are not the element with the scrollbar.
绑定到document
或window
不起作用,因为在这种情况下它们不是带有滚动条的元素。
Working Live Demo:
工作现场演示:
$(document).ready(function () {
var scroll_pos = 0;
$("#left-panel").scroll(function () {
scroll_pos = $(this).scrollTop();
if (scroll_pos > 210) {
$("#left-panel").css('background-color', '#1A1A1A');
} else {
$("#left-panel").css('background-color', 'red');
}
console.log(scroll_pos);
});
});
#left-panel {
position: fixed;
top: 0;
left: 0;
width: 80%;
height: 100%;
z-index: 2;
overflow:auto;
height:2000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="left-panel">
<div style="height:5000px;">CONTENT</div>
</div>
JSFiddle Version: http://jsfiddle.net/ncuydr9y/1/
JSFiddle 版本:http: //jsfiddle.net/ncuydr9y/1/