問題:在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: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
計算高度
總結
以上所述是小編給大家介紹的解決HTML5中滾動到底部的事件問題,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回覆大家的。在此也非常感謝大家對VeVb武林網站的支持!
如果你覺得本文對你有幫助,歡迎轉載,煩請註明出處,謝謝!