11.滚轮事件.html 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  6. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7. <title>Document</title>
  8. <style>
  9. #box1 {
  10. width: 100px;
  11. height: 100px;
  12. background-color: red;
  13. }
  14. </style>
  15. <script>
  16. window.onload = function () {
  17. /**
  18. * 当鼠标滚轮向下滚动时,box1变长
  19. * 当滚轮向上滚动时,box1变短
  20. */
  21. //获取id为box1的div
  22. var box1 = document.getElementById('box1');
  23. //为box1绑定一个鼠标滚轮滚动的事件
  24. /**
  25. * onmousewheel鼠标滚轮滚动的事件,会在滚轮滚动时触发,
  26. * 但是火狐不支持该属性
  27. *
  28. * 在火狐中需要使用DOMMouseScroll来绑定滚动事件
  29. * 该事件需要通过addEventListener()函数来绑定
  30. */
  31. // box1.onmousewheel = function () {
  32. // alert('滚了');
  33. // };
  34. //为火狐绑定滚轮事件
  35. // bind(box1,"DOMMouseScroll",function(){
  36. // alert('滚了');
  37. // });
  38. //上面两条语句可以写成下面的格式
  39. box1.onmousewheel = function () {
  40. alert('滚了');
  41. };
  42. bind(box1,"DOMMouseScroll",box1.onmousewheel);
  43. //或者把两个函数提取出来
  44. // function fun() {
  45. // alert('滚了');
  46. // };
  47. // box1.onmousesheel = fun;
  48. // bind(box1, "DOMMouseScroll", fun);
  49. };
  50. function bind(obj, eventStr, callback) {
  51. if (obj.addEventListener) {
  52. //大部分浏览器兼容的方式
  53. obj.addEventListener(eventStr, callback, false);
  54. } else {
  55. /**
  56. * this是谁由调用方式决定
  57. * callback.call(obj):call方法可以修改this
  58. */
  59. //IE8及以下
  60. obj.attachEvent("on" + eventStr, function () {
  61. //在匿名函数中调用回调函数
  62. callback.call(obj);
  63. });
  64. }
  65. }
  66. </script>
  67. </head>
  68. <body>
  69. <div id="box1"></div>
  70. </body>
  71. </html>