問題:在H5中,我們有這樣的需求:例如有列表的時候,滾動到底部時,需要加載更多。
解決方案:可以采用window的滾動事件進行處理
分析:如果滾動是針對整個屏幕而言的(不針對于某個界面小塊),那么這個應該是是成立的:屏幕的高度+最大滾動的距離 = 內(nèi)容的高度
代碼實現(xiàn):
<html> <head> <meta charset="UTF-8"> <title>監(jiān)聽滾動到底部滾動底部</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是為了保證一定的彈性,并非要剛好相等才出發(fā), if(height-5<=scrollTop+clientHeight&&scrollTop+clientHeight<=height+5){ console.log('監(jiān)聽成功','到達底部') } } } </script></html>
代碼的相關(guān)說明:很多時候,列表加載,我們不能夠把裝載子元素的父容器高度設(shè)死,此時采用style設(shè)置為auto時,element.style.height
也會等于auto ,建議采用clientHeight
或者利用計算樣式 getComputedStyle
計算高度
總結(jié)
以上所述是小編給大家介紹的解決HTML5中滾動到底部的事件問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對武林網(wǎng)網(wǎng)站的支持!
如果你覺得本文對你有幫助,歡迎轉(zhuǎn)載,煩請注明出處,謝謝!
新聞熱點
疑難解答