H5中滾動到底部的事件

問題:在H5中,咱們有這樣的需求:例若有列表的時候,滾動到底部時,須要加載更多。html

解決方案:能夠採用window的滾動事件進行處理spa

分析:若是滾動是針對整個屏幕而言的(不針對於某個界面小塊),那麼這個應該是是成立的:屏幕的高度+最大滾動的距離 = 內容的高度code

代碼實現:htm

<html> 

    <head> 

    <meta charset="UTF-8">

        <title>監聽滾動到底部滾動底部</title> 

        <style> 
.div2{
width:100px;
height:100px;
border:1px solid red
}
*{
margin:0

}
.button1:active{
   background:red
}
body{
height:375px;
width:667px;
border:1px solid red

}
.div1{

height:600px;
width:100%;
background:red
}
.div2{

height:600px;
width:100%;
background:green
}

.div3{

height:600px;
width:100%;
background:blue
}
.div4{

height:600px;
width:100%;
background:yellow
}


        </style> 

    </head> 
   

        

    <body > 
    <div class="div0">
    <div class="div1"></div>
    <div class="div2"></div>
    <div class="div3"></div>
    <div class="div4"></div>
    <div class="div5"></div>
    
    
    </div>

    </body> 
 
    <script>
    window.onload = function(){
  //獲取容器父元素
    var div0 = document.getElementsByClassName('div0')[0];
    //height 計算屬性的高度
    var height = parseInt((window.getComputedStyle(div0, null).height).replace('px', ''));
    
    console.log(height,"div0的計算高度")
    
    window.onscroll = function(){
/*
scrollTop 爲滾動條頂端距離界面右上角的距離,這裏採用了兼容性寫法

*/
let scrollTop = document.documentElement && document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
//+-5是爲了保證必定的彈性,並不是要恰好相等纔出發,
if(height-5<=scrollTop+clientHeight&&scrollTop+clientHeight<=height+5){ console.log('監聽成功','到達底部') } } } </script> </html>

代碼的相關說明:不少時候,列表加載,咱們不可以把裝載子元素的父容器高度設死,此時採用style設置爲auto時,element.style.height也會等於auto ,建議採用clientHeight或者利用計算樣式 getComputedStyle計算高度blog

相關文章
相關標籤/搜索