12.滚轮事件二.html 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. //获取id为box1的div
  18. var box1 = document.getElementById('box1');
  19. //为box1绑定一个鼠标滚轮滚动的事件
  20. /**
  21. * onmousewheel鼠标滚轮滚动的事件,会在滚轮滚动时触发,
  22. * 但是火狐不支持该属性
  23. *
  24. * 在火狐中需要使用DOMMouseScroll来绑定滚动事件
  25. * 该事件需要通过addEventListener()函数来绑定
  26. */
  27. box1.onmousewheel = function (event) {
  28. event = event || window.event;
  29. //event.wheelDelta可以获取鼠标滚轮滚动的方向
  30. //向上滚150,向下滚-150
  31. //wheelDelta这个值我们不看大小,只看正负
  32. // alert(event.wheelDelta);
  33. //wheelDelta这个属性火狐中不支持
  34. //在火狐中使用event.detail来获取滚动的方向
  35. //向上滚是负值,向下滚是正值
  36. // alert(event.detail);
  37. /**
  38. * 当鼠标滚轮向下滚动时,box1变长
  39. * 当滚轮向上滚动时,box1变短
  40. */
  41. //判断鼠标滚轮滚动的方向
  42. if (event.wheelDelta > 0 || event.detail < 0) {
  43. // alert("向上滚");
  44. //向上滚,box1变短
  45. box1.style.height = box1.clientHeight - 10 + "px";
  46. } else {
  47. // alert("向下滚");
  48. //向下滚,box1变长
  49. box1.style.height = box1.clientHeight + 10 + "px";
  50. };
  51. /**
  52. * 使用addEventListener()方法绑定响应函数,取消默认行为时不能使用return false
  53. * 需要使用event来取消默认行为event.preventDefault();
  54. * 但是IE8不支持event.preventDefault();如果直接使用会报错
  55. */
  56. //event.preventDefault();
  57. event.preventDefault() && event.preventDefault();
  58. /**
  59. * 当滚轮滚动时,如果浏览器有滚动条,滚动条会随之滚动,
  60. * 这是浏览器的默认行为,如果不希望发生,则可以取消默认行为
  61. */
  62. return false;
  63. };
  64. //为火狐绑定滚轮事件
  65. bind(box1, "DOMMouseScroll", box1.onmousewheel);
  66. };
  67. function bind(obj, eventStr, callback) {
  68. if (obj.addEventListener) {
  69. //大部分浏览器兼容的方式
  70. obj.addEventListener(eventStr, callback, false);
  71. } else {
  72. /**
  73. * this是谁由调用方式决定
  74. * callback.call(obj):call方法可以修改this
  75. */
  76. //IE8及以下
  77. obj.attachEvent("on" + eventStr, function () {
  78. //在匿名函数中调用回调函数
  79. callback.call(obj);
  80. });
  81. }
  82. }
  83. </script>
  84. </head>
  85. <body style="height: 2000px;">
  86. <div id="box1"></div>
  87. </body>
  88. </html>