<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=\, initial-scale=1.0">
<title>Document</title>
<style type="text/css">
#box1 {
width: 100px;
height: 100px;
background-color: red;
}
</style>
<script type="text/javascript">
window.onload = function () {
/*
*鼠标轮向下滚动时,box1变长
*鼠标轮向下滚动时,box1变短
*/
var box1 = document.getElementById("box1");
box1.onmousewheel = function (event) {
event = event || window.event;
//判断滚轮滚动的方向
//alert(event.wheelDelta);
//火狐中不支持,现在在火狐使用detail
//alert(event.detail);
if (event.wheelDelta > 0 || event.detail < 0) {
//向下滚动时,box1变短
box1.style.height = box1.clientHeight + 10 + "px";
} else {
//向下滚动时,box1变长
box1.style.height = box1.clientHeight - 10 + "px";
}
//当滚动条滚动时,如果浏览器有滚动条,滚动条会随之发生改变,效果会变差
//这是浏览器的默认行为,如果不希望发生,我们可以取消默认行为
//火狐不支持取消这种默认行为的方式,要用preventDefault();
event.preventDefault && event.preventDefault();
return false;
/*
onmousewheel:鼠标滚轮滚动事件,会在滚轮滚动时触发,
但是火狐不支持该属性
在火狐中,要使用DOMMouseScroll
注意该事件需要通过addEventListener()函数来绑定
*/
};
bind(box1, "DOMMouseScroll", box1.onmousewheel);
function bind(obj, eventStr, callback) {
if (obj.addEventListener) {
//大部分兼容的方式
obj.addEventListener(eventStr, callback, false);
} else {
/*
*this是谁由调用方式决定
*callback.call(obj)
*/
//ie8以下
obj.attachEvent("on" + eventStr, function () {
callback.call(obj);
});
}
};
};
</script>
</head>
<body style="height: 2000px;">
<div id="box1"></div>
</body>
</html>
2022/1/15,滚轮的事件
最新推荐文章于 2024-06-14 15:02:13 发布