滚动时使元素可见

时间:2018-10-18 06:12:12

标签: javascript html css scroll visibility

我对如何使元素在用户滚动时可见可见感到困惑,这是我的代码:

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>

2 个答案:

答案 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)

尝试一下,我对您的代码段做了一些更改

  • onscroll事件已添加
  • 已更改的Benefitpub.style.visibility ='visible';受益于pub.style.visibility ='inherit';

#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