我的页面上有不同的部分,如下所示:
<div class="red" data-section="Section Red"></div>
<div class="blue" data-section="Section Blue"></div>
<div class="yellow" data-section="Section Yellow"></div>
<div class="green" data-section="Section Green"></div>
还有一个像这样的单独的div:
<div class="current_div"></div>
该div始终位于页面顶部。如何设置,以便当用户滚动到blue
(或任何其他)div时,current_div
将更改为:
<div class="current_div">Section Blue</div>
这是我的标记的小提琴:https://jsfiddle.net/wb7L954v/1/
必须有一种简单的方法来获取data-section
部分并将其简单地放入该div中?
答案 0 :(得分:5)
步骤:
data-section
属性scroll
event do
scrollTop
大于该元素&#39; offsetTop
,那就是我们正在寻找的元素data-section
属性值写入相应的标题元素答案 1 :(得分:2)
这是一个适用于每个滚动方向的示例。
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/
如果你需要向上和向下滚动,那么你可以使用这个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));
};
答案 2 :(得分:1)
您需要将每个彩色部分的offSet顶部与主div进行比较。
$( window ).scroll(function() {
var $div = $(".current_div").offset().top;
if($div >= $(".red").offset().top)
$(".current_div").text("Section Red");
if($div >= $(".blue").offset().top)
$(".current_div").text("Section Blue");
if($div >= $(".yellow").offset().top)
$(".current_div").text("Section Yellow");
if($div >= $(".green").offset().top)
$(".current_div").text("Section Green");
});