js實現的仿Photoshop滑鼠滾輪控制輸入框取值(修正相容Chrome)_javascript技巧

來源:互聯網
上載者:User
一直很想做這個效果,原理是監聽滑鼠滾輪事件;可將此效果繼續發散到其他應用上,如圖片縮放,頁面縮放等。
<!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=gb2312" /> <title>滾輪效果 -http://www.51obj.cn/</title> </head> <body> <input type="text" id="txt" value="0" /> <script type="text/javascript"> var oTxt=document.getElementById("txt"); /*********************** * 函數:判斷滾輪滾動方向 * 參數:event * 返回:滾輪方向 1:向上 -1:向下 *************************/ var scrollFunc=function(e){ var direct=0; e=e || window.event; if(e.wheelDelta){ direct=e.wheelDelta>0?1:-1; }else if(e.detail){ direct=e.detail<0?1:-1; } ScrollText(direct); } /**************************** * 函數:控制文字框文字 * 參數:滾輪方向(由scrollFunc返回) * 返回:無 *******************************/ function ScrollText(arg){ oTxt.focus(); var _value=parseInt(oTxt.value); if(arg>0){ _value++; }else{ _value--; } oTxt.value=_value; oTxt.select();//選取效果 } /*註冊事件*/ if(document.addEventListener){ document.addEventListener('DOMMouseScroll',scrollFunc,false); }//W3C window.onmousewheel=document.onmousewheel=scrollFunc;//IE/Opera/Chrome </script> </body> </html>
[Ctrl+A 全選 注:如需引入外部Js需重新整理才能執行]

已經ff、ie、opera、chrome測試;其中45~47行中若使用 
複製代碼 代碼如下:

/*註冊事件*/
if(document.attachEvent){
document.attachEvent('onmousewheel',scrollFunc);
}else if(document.addEventListener){
document.addEventListener('DOMMouseScroll',scrollFunc,false);
}

則Chrome不起作用,將其更改為
複製代碼 代碼如下:

/*註冊事件*/
if(document.addEventListener){
document.addEventListener('DOMMouseScroll',scrollFunc,false);
}//W3C
window.onmousewheel=document.onmousewheel=scrollFunc;//IE/Opera/Chrome

即可。 
作者:王洪劍(51obj)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.