我是靠谱客的博主 耍酷彩虹,这篇文章主要介绍JavaScript解决浏览器兼容性问题(五)—— 滚轮事件问题描述实例问题分析代码解疑,现在分享给大家,希望可以做个参考。

问题描述

        onmousewheel鼠标滚轮滚动的事件,会在滚轮滚动时触发,但是火狐不支持该属性;

        如果当前页面中有滚动条,想要对元素触发鼠标滚轮滚动事件时,即时鼠标在目标元素上,页面还是会随着滚轮的滚动。

实例

        名称

                自由伸缩金箍棒

        功能简介

                当鼠标在方块上时,实现鼠标滚轮向下滑方块变长,向上滑方块变短

        源代码

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> #box1 { width: 100px; height: 100px; background-color: red; } </style> <script type="text/javascript"> window.onload = function () { var box1 = document.getElementById("box1"); //为浏览器绑定鼠标滚轮事件 box1.onmousewheel = function (event) { event = event || window.event; //event.wheelDelta 可以获取鼠标滚轮滚动的方向,火狐中不支持 //在火狐中使用event.detail来获取 if (event.wheelDelta > 0 || event.detail < 0) { box1.style.height = box1.clientHeight - 10 + "px"; } else { box1.style.height = box1.clientHeight + 10 + "px"; } //取消火狐浏览器默认行为(因为是用addEventListener,所以必须用此方法来取消) event.preventDefault && event.preventDefault(); //取消浏览器默认行为 return false; }; //为火狐浏览器绑定鼠标 bind(box1, "DOMMouseScroll", box1.onmousewheel); }; function bind(obj, eventStr, callback) { if (obj.addEventListener) { obj.addEventListener(eventStr, callback, false); } else { obj.attachEvent("on" + eventStr, function () { callback.call(obj); }); } } </script> </head> <body style="height: 2000px;"> <div id="box1"></div> </body> </html>

问题分析

        ①  onmousewheel鼠标滚轮滚动的事件,会在滚轮滚动时触发,但是火狐不支持该属性,在火狐中需要使用 DOMMouseScroll 来绑定滚动事件,但是注意该事件需要通过addEventListener()函数来绑定。

        ②  需要判断滚轮是向上滚动还是向下滚动,wheelDelta 可以获取鼠标滚轮滚动的方向,但这个属性火狐中不支持,在火狐中使用event.detail来获取滚动的方向。

        ③  为了解决浏览器滚动条肆意滚动的问题,需要解除浏览器的默认行为,return false; 可以有效解决,但是它仅适用于未使用addEventListener来绑定响应函数的浏览器,对于使用的,则需要使用event.preventDefault();来取消默认行为。

代码解疑

复制代码
1
bind(box1, "DOMMouseScroll", box1.onmousewheel);

        bind函数我们在第三篇中已经创建好了,其中第三个参数是回调函数,可以直接把上面写好的滚轮响应事件作为回调函数,虽然火狐中不支持onmousewheel,但是box1.onmousewheel可以作为函数名来调用。

最后

以上就是耍酷彩虹最近收集整理的关于JavaScript解决浏览器兼容性问题(五)—— 滚轮事件问题描述实例问题分析代码解疑的全部内容,更多相关JavaScript解决浏览器兼容性问题(五)——内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(54)

评论列表共有 0 条评论

立即
投稿
返回
顶部