gpt4 book ai didi

javascript - 在视口(viewport)内显示一个 div

转载 作者:行者123 更新时间:2023-11-28 05:32:59 25 4
gpt4 key购买 nike

我有10个div元素,宽高都是500px;

<div class="cont_1">a lots of content here..</div>
<div class="cont_2">a lots of content here..</div>
<div class="cont_3">a lots of content here..</div>
<div class="cont_4">a lots of content here..</div>
<div class="cont_5">a lots of content here..</div>
<div class="cont_6">a lots of content here..</div>
<div class="cont_7">a lots of content here..</div>
<div class="cont_8">a lots of content here..</div>
<div class="cont_9">a lots of content here..</div>
<div class="cont_10">a lots of content here..</div>

和我的CSS

div{
width:500px;
height:500px;
background:#f0f0f0;
border:1px solid #ccc;
margin:10px;
padding:10px;
}

我的第七个 div 是用 display:none 隐藏的。一旦用户滚动到该元素,我该如何显示它?

最佳答案

您必须将滚动事件附加到页面以在滚动后检查每个元素的位置:

function CheckIfVisible(elem){
var ElemPos = elem.getBoundingClientRect().top;
elem.style.display = (ElemPos > 0 && ElemPos < document.body.parentNode.offsetHeight)?"block":"none";
}

window.addEventListener("onscroll", function(){
var elem = document.getElementsByClassName("cont_1")[0];
CheckIfVisible(elem);
});

window.addEventListener("onscroll", function(){
var elem = document.getElementsByClassName("cont_2")[0];
CheckIfVisible(elem);
});

window.addEventListener("onscroll", function(){
var elem = document.getElementsByClassName("cont_3")[0];
CheckIfVisible(elem);
});

等等...

关于javascript - 在视口(viewport)内显示一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38405916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com