最近在一個項目中,在寫前端頁面的時候,想像以前做Android時在頁面時刻監聽上下滾動的事件,查找資料發現由鼠標或類似用戶動作觸發的事件有以下圖示:

不多說了,直接上代碼了,經過測試可以使用:
<!DOCTYPE html><html> <head> <meta charset="utf-8" /> <title>Dome</title> <script type="text/javascript"> function scroll(){ //console.log("打印log日志");實時看下效果 console.log("開始滾動!"); } var scrollFunc = function (e) { e = e || window.event; if (e.wheelDelta) { //第一步:先判斷瀏覽器IE,谷歌滑輪事件 if (e.wheelDelta > 0) { //當滑輪向上滾動時 console.log("滑輪向上滾動"); } if (e.wheelDelta < 0) { //當滑輪向下滾動時 console.log("滑輪向下滾動"); } } else if (e.detail) { //Firefox滑輪事件 if (e.detail> 0) { //當滑輪向上滾動時 console.log("滑輪向上滾動"); } if (e.detail< 0) { //當滑輪向下滾動時 console.log("滑輪向下滾動"); } } } //給頁面綁定滑輪滾動事件 if (document.addEventListener) {//firefox document.addEventListener('DOMMouseScroll', scrollFunc, false); } //滾動滑輪觸發scrollFunc方法 //ie 谷歌 window.onmousewheel = document.onmousewheel = scrollFunc; </script> </head> <body onscroll="scroll()"> <div style="height: 2000px;background-color: aqua;"></div> </body></html>如果有沒有使用過console.log(“”)的,我這里截下圖看下吧(谷歌瀏覽器):

以上這篇js監聽html頁面的上下滾動事件方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持武林網。
新聞熱點
疑難解答