H5中滾動到底部的事件


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

解決方案:可以采用window的滾動事件進行處理

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

代碼實現:

<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計算高度


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM