我有几个 id="scroll_1"、"scroll_2"、"scroll_3" 等的 div...当这些 div 中的任何一个位于窗口的中心时,我想使用 jQuery 突出显示和/或更改背景颜色无论哪个 div 位于窗口的中心。目前,背景颜色一旦位于屏幕中心就会发生变化,但是一旦它不再位于中心,我就会遇到将其更改回原始背景颜色的问题(即用户向下/向上滚动到另一个 scroll_x id。
编辑我拥有的唯一相关的 CSS 代码是:
[id^=scroll_]{
background-color:white;
}
谢谢您的帮助!
<script>
$(document).ready(function() {
var window_height = $(window).height();
var obj_height = $('#scroll_1').height(); //height of object we are scrolling past
var top = $('#replyer').offset().top + (obj_height /2); //position on screen to start highlighting #scroll_x
$(window).scroll(function() {
var scrollMiddle = $(window).scrollTop() + ((window_height/2) - (obj_height /2));
if (scrollMiddle >= top) {
var scrollPosition = $(document).scrollTop()+ ((window_height/2) - (obj_height /2)),
currentPosition = 0;
$('div[id^="scroll_"]').each(function() {//iterate over #scroll_x and only change background until another #scroll_x is in the middle of the screen
currentPosition = $(this).offset().top;
if (currentPosition >= scrollPosition) {
$(this).prev(function(){
$(this).css('background-color',"#aaa"); //change previous #scroll_x back to original background color - Not Working Currently
});
return false; // break the loop
}
$(this).css('background-color',"#ccc"); //currently changes background of #scroll_x once in middle of screen but stays highlighted when scrolling up/down to previous/next iteration of #scroll_x
});
}
});
});
</script>
html:
<div id="replyer">
Top line before repeating divs
</div>
<div id="scroll_1">
First object to scroll over.
</div>
<div id="scroll_2">
Want to highlight div currently in the middle of screen
</div>
<div id="scroll_3">
Only div in middle of screen should be highlighted (background change)
</div>