admin管理员组文章数量:1323715
/
BG color should be #1A1A1A on start then change after scrolling 210 px. Not sure where I'm going wrong.
$(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');
}
});
});
http://jsfiddle/ncuydr9y/
BG color should be #1A1A1A on start then change after scrolling 210 px. Not sure where I'm going wrong.
$(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');
}
});
});
Share
Improve this question
edited Feb 24, 2017 at 10:27
neophyte
6,6242 gold badges31 silver badges43 bronze badges
asked Sep 20, 2015 at 3:50
user2252219user2252219
8653 gold badges17 silver badges42 bronze badges
1 Answer
Reset to default 3You 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).
Binding to document
or window
won't work, because in this case they are not the element with the scrollbar.
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./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/ncuydr9y/1/
本文标签: javascriptChanging background color of div on scrollStack Overflow
版权声明:本文标题:javascript - Changing background color of div on scroll - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742125454a2421918.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论