12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182 |
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8">
- <meta http-equiv="X-UA-Compatible" content="IE=edge">
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>Document</title>
- <style>
- #box1 {
- width: 100px;
- height: 100px;
- background-color: red;
- }
- </style>
- <script>
- window.onload = function () {
- /**
- * 当鼠标滚轮向下滚动时,box1变长
- * 当滚轮向上滚动时,box1变短
- */
- //获取id为box1的div
- var box1 = document.getElementById('box1');
- //为box1绑定一个鼠标滚轮滚动的事件
- /**
- * onmousewheel鼠标滚轮滚动的事件,会在滚轮滚动时触发,
- * 但是火狐不支持该属性
- *
- * 在火狐中需要使用DOMMouseScroll来绑定滚动事件
- * 该事件需要通过addEventListener()函数来绑定
- */
- // box1.onmousewheel = function () {
- // alert('滚了');
- // };
- //为火狐绑定滚轮事件
- // bind(box1,"DOMMouseScroll",function(){
- // alert('滚了');
- // });
- //上面两条语句可以写成下面的格式
- box1.onmousewheel = function () {
- alert('滚了');
- };
- bind(box1,"DOMMouseScroll",box1.onmousewheel);
- //或者把两个函数提取出来
- // function fun() {
- // alert('滚了');
- // };
- // box1.onmousesheel = fun;
- // bind(box1, "DOMMouseScroll", fun);
- };
- function bind(obj, eventStr, callback) {
- if (obj.addEventListener) {
- //大部分浏览器兼容的方式
- obj.addEventListener(eventStr, callback, false);
- } else {
- /**
- * this是谁由调用方式决定
- * callback.call(obj):call方法可以修改this
- */
- //IE8及以下
- obj.attachEvent("on" + eventStr, function () {
- //在匿名函数中调用回调函数
- callback.call(obj);
- });
- }
- }
- </script>
- </head>
- <body>
- <div id="box1"></div>
- </body>
- </html>
|