我对如何使元素在用户滚动时可见可见感到困惑,这是我的代码:
var benefitpub = document.getElementById('pubbox');
var advbox2 = document.getElementById('advbox');
if (document.body.scrollTop > benefitpub.getBoundingClientRect().top + 'px') {
benefitpub.style.visibility = 'visible';
}
if (document.body.scrollTop > advbox2.getBoundingClientRect().top + 'px') {
advbox2.style.visibility = 'visible';
}
#advbox, #pubbox{
margin-top: 500px;
visibility: hidden;
}
<div id="advbox">
Hello This is advbox
</div>
<div id="pubbox">
Hello this is Pubbox
</div>
答案 0 :(得分:3)
您将需要进行一些更改,首先,您需要一个onscroll
事件处理程序,以便可以检查用户何时滚动窗口。
var benefitpub = document.getElementById('pubbox');
var advbox2 = document.getElementById('advbox');
window.onscroll = function () {
if (document.documentElement.scrollTop > benefitpub.getBoundingClientRect().top) {
benefitpub.style.visibility = 'visible';
} else {
benefitpub.style.visibility = 'hidden';
}
if (document.documentElement.scrollTop > advbox2.getBoundingClientRect().top) {
advbox2.style.visibility = 'visible';
} else {
advbox2.style.visibility = 'hidden';
}
}
#advbox, #pubbox{
margin-top: 500px;
visibility: hidden;
}
<div id="advbox">
Hello This is advbox
</div>
<div id="pubbox">
Hello this is Pubbox
</div>
另外,请注意,我得到的是scrollTop
标签的documentElement
的{{1}},而不是正文,因为它返回了<html>
。
答案 1 :(得分:1)
尝试一下,我对您的代码段做了一些更改
#advbox, #pubbox,#pubbox1{
margin-top: 500px;
visibility: hidden;
}
<div id="advbox">
Hello This is advbox
</div>
<div id="pubbox">
Hello this is Pubbox
</div>
<div id="pubbox1">
Hello this is Pubbox
</div>
get foo.html