今天弄了一個東西,頁面本來是橫向,所以底部有橫向滾動條,豎著就沒有滾動條了,現在要求是鼠標滑輪要左右滾動,這就需要寫js代碼來實現了,寫這個的過程中遇到很大麻煩
ie 火狐 chrome 三個瀏覽器支持的函數完全不一樣,真是瘋啦。
這里有幾個知識點說明一下
監控滑輪的事件
ie:onmousewheel
firfox:DOMMouseScroll
chrome:mousewheel
哎真是無語
滾動的返回值也是不一樣的
firfox用detail 返回 +-3
其他的用wheelDelta 返回 +-120
有返回值判斷滾動的方向
還有一般瀏覽器除了chrome判斷頁面的左移動用document.documentElement.scrollLeft
但是chrome瀏覽器要用document.body.scrollLeft
好了代碼分享如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>無標題文檔</title></head> <body><div id="test" style="width:3000px; height:500px; background:#666;"></div><script language="javascript"> var dbody=document.getElementById('test');//ff用objAddEvent(document,'DOMMouseScroll', function(e){return mouse_scroll(e);}) //非ff chrome 用objAddEvent(document,'mousewheel', function(e){return mouse_scroll(e);}) //chrome用objAddEvent(dbody,'mousewheel', function(e){return mouse_scroll(e);})function mouse_scroll(e){e=e || window.event;var delD=e.wheelDelta?e.wheelDelta: -e.detail*40;//判斷上下方向var move_s=delD>0?-50:50;document.documentElement.scrollLeft+=move_s; //非chrome瀏覽器用這個//chrome瀏覽器用這個if(document.documentElement.scrollLeft==0)document.body.scrollLeft+=move_s; return false;}//這個是給對象增加監控方法的函數function objAddEvent(oEle, sEventName, fnHandler){if(oEle.attachEvent) oEle.attachEvent('on'+sEventName, fnHandler);else oEle.addEventListener(sEventName, fnHandler, false);} </script></body></html>
這個代碼其實有點問題就是在chrome瀏覽器下只有鼠標放到那個灰色內才能滑動,這個問題我一直沒有解決掉,如果那個高手解決可以留言告訴我,謝謝了。
新聞熱點
疑難解答