這是爲每一個滾動方向工作的例子。
HTML:
<div class="current_div">current div</div>
<div class="red" data-section="Section Red">red</div>
<div class="blue" data-section="Section Blue">blue</div>
<div class="yellow" data-section="Section Yellow">yellow</div>
<div class="green" data-section="Section Green">green</div>
CSS(測試):
*{margin: 0;}
.current_div{position: fixed;background: #ccc;top: 0;width: 100%;}
.red, .blue, .yellow, .green{height: 500px;}
.red{background: red;}
.blue{background: blue;}
.yellow{background: yellow;}
.green{background: green;}
的jQuery:
$.fn.isOnScreen = function() {
var win = $(window);
var viewport = {
top: win.scrollTop(),
left: win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();
var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
var currentDiv = $('.current_div');
$(window).scroll(function() {
if ($('.red').isOnScreen() == true) {
currentDiv.text($('.red').data('section'));
}
else if($('.blue').isOnScreen() == true){
currentDiv.text($('.blue').data('section'));
}
else if($('.yellow').isOnScreen() == true){
currentDiv.text($('.yellow').data('section'));
}
else if($('.green').isOnScreen() == true){
currentDiv.text($('.green').data('section'));
}
});
工作例如:https://jsfiddle.net/1aakar8s/1/
如果需要上下滾動小號o你可以使用這個jQuery代碼:
$.fn.isOnScreen = function() {
var win = $(window);
var viewport = {
top: win.scrollTop(),
bottom: this.top + win.height()
};
var bounds = this.offset();
bounds.bottom = bounds.top + this.outerHeight();
return (!(viewport.bottom < bounds.top || viewport.top > bounds.bottom));
};
這看起來像你還沒有研究過它。在問之前,你應該搜索。不過,我會給你一個[提示](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollTop) –
我確實在搜索,但我不知道它會是什麼調用。我花了12小時搜索(不是開玩笑)。我發現最接近的是Bootstrap樣式菜單,它突出顯示了當前部分,但不幸的是,這並沒有幫助我理解div中的「數據部分」部分。在寫這裏之前,我已經用盡了幾乎所有選項,相信我:) – user1996496
感謝[this](http://stackoverflow.com/questions/6597904/scrollable-div-which-elements-can-be-seen)http: //jsfiddle.net/U4qyp/32/ –