注意:测试时鼠标一定要放在图形上。
效果如下:
①当鼠标往上滚动:
②当鼠标往下滚动:
代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>鼠标滚动事件</title>
<style type="text/css">
#box1{
width: 100px;
height:80px;
background: magenta;
}
</style>
<script type="text/javascript">
window.onload = function () {
var box1 = document.getElementById("box1");
// alert(box1.style.height);
box1.onmousewheel = function (event) {
event = event || window.event;/*||为或语句,当IE不能识别event时候,就执行window.event 赋值*/
console.log(event.detail);//火狐
if(event.wheelDelta > 0 || event.detail < 0){/*可通过控制台查看,第一个针对谷歌,第二个针对火狐*/
// console.log(event.wheelDelta);/*控制台测试代码*/
/*每向上滑动则图形缩短*/
box1.style.height = box1.clientHeight - 10 + "px";
}else {
/*向下滑动则加长*/
box1.style.height = box1.clientHeight + 10 + "px";
}
event.preventDefault && event.preventDefault();
return false;
};
}
/*为火狐绑定滚动事件*/
bind(box1,"DOMMouseScroll",box1.onmousewheel);
function bind(obj,eventStr,callback) {
obj.addEventListener(eventStr,callback,false);
}
</script>
</head>
<body>
<div id="box1"></div>
</body>
</html>