现在我有div显示滚动超过某个标记但显示在浏览器调整大小时它会被破坏。有什么方法可以让我做出回应吗?我不确定是否添加$(window).resize(checkY);也会工作。
编辑: 最终目标是在关联内容进入视图时显示标题
HTML
<div class="title" data-position="400,1150">Yama</div>
<div class="title" data-position="1150,1800">Modurra</div>
<div class="title" data-position="1800,2600">Computer</div>
<div class="title" data-position="2600,3300">Maru</div>
<div class="title" data-position="3300,3900">Sushi</div>
<div class="title" data-position="3900,4700">Summit</div>
<div class="title" data-position="4700,10000">Lights Out</div>
JS
<script>
//Note you do not need to make an anonymous
//function just to do the call for checkY
//just pass the function
$(window).scroll(checkY);
function checkY() {
//save this value so we dont have to call the function everytime
var top = $(window).scrollTop();
console.log(top);
$(".title").each(function () {
var positionData = $(this).data("position").split(",");
if (top > positionData[0] && top <= positionData[1]) {
console.log("Show");
$(this).show();
} else {
console.log("Hide");
$(this).hide();
}
});
}
checkY();
</script>
修改
.title {
position:fixed;
top:0px;
left:45%;
display:none;
padding:10px;
background:rgba(255,255,255,0);
color:#000;}
#Yama {
position:absolute;
display:block;
height:900px;
font-family: Arial, Helvetica, sans-serif;
font-size:70pt;
letter-spacing:0px;
font-weight:100;
-webkit-font-smoothing: antialiased;
text-align:center;}
这是保存所有内容的包装器。
#mini {width:100%; height:100%;
padding-top:140px;}
答案 0 :(得分:2)
您要做的是找到目标内容并确定该元素是否在视口中。如果是,那么你显示标题。
有了这个,你不需要使用data- *属性。您可以将标题放在主要内容的元素中,然后使用jQuery的.closest方法获取最接近的父元素(内容元素)。从那里做测试。
HTML
<div id="Yama" class="content">
<div class="title">Yama</div>
</div>
<div id="Modurra" class="content">
<div class="title">Modurra</div>
</div>
<div id="Computer" class="content">
<div class="title">Computer</div>
</div>
<div id="Maru" class="content">
<div class="title">Maru</div>
</div>
<div id="Sushi" class="content">
<div class="title">Sushi</div>
</div>
<div id="Summit" class="content">
<div class="title">Sushi</div>
</div>
<div id="LightsOut" class="content">
<div class="title">Lights Out</div>
</div>
JS
$(window).scroll(checkY);
function checkY(){
var top = $(window).scrollTop();
$(".title").each(function(){
var target = $(this).closest(".content");
//The start range value is just offset().top
var tTop = target.offset().top;
//The end range value is the start range value plus
//the content elements height
var tBottom = tTop+target.outerHeight();
if(top >= tTop && top <= tBottom){
console.log("Show");
$(this).show();
} else {
console.log("Hide");
$(this).hide();
}
});
}
checkY();