js如何判断鼠标滚动方向

 时间:2026-04-30 03:20:20

1、新建一个html代码页面,在这个代码页面创建一个<img>标签,然后给这个<img>标签引入一个图片路径。如图:

js如何判断鼠标滚动方向

2、设置鼠标滚动事件。向上滚动鼠标就弹出一个mouseup文字,向下滚动鼠标就弹出mousedown。如图:

JavaScript代码:

<script type="text/javascript">

window.onload = function(){

/*滚轮事件只有firefox比较特殊,使用DOMMouseScroll; 其他浏览器使用mousewheel;*/

// firefox

var direction;

document.body.addEventListener("DOMMouseScroll", function(event) {

   direction= event.detail && (event.detail > 0 ? "mousedown" : "mouseup");

   alert(direction)

});

// chrome and ie

document.body.onmousewheel = function (event) {

   event = event || window.event;

   direction = event.wheelDelta && (event.wheelDelta > 0 ? "mouseup" : "mousedown");

   console.log(direction);

   alert(direction)

};

}

</script>

js如何判断鼠标滚动方向

3、保存html代码文件后使用浏览器打开,在图片上滚动鼠标就会弹出向上或向下的文字提示。效果如图:

js如何判断鼠标滚动方向

js如何判断鼠标滚动方向

4、所有代码。可以直接复制所有代码粘贴到新建的html文件,保存后运行即可看到效果。

所有代码:

<!DOCTYPE html>

<html>

<head>

<meta charset="UTF-8">

<title></title>

<script type="text/javascript">

window.onload = function(){

/*滚轮事件只有firefox比较特殊,使用DOMMouseScroll; 其他浏览器使用mousewheel;*/

// firefox

var direction;

document.body.addEventListener("DOMMouseScroll", function(event) {

   direction= event.detail && (event.detail > 0 ? "mousedown" : "mouseup");

   alert(direction)

});

// chrome and ie

document.body.onmousewheel = function (event) {

   event = event || window.event;

   direction = event.wheelDelta && (event.wheelDelta > 0 ? "mouseup" : "mousedown");

   console.log(direction);

   alert(direction)

};

}

</script>

<style type="text/css">

img{

width: 630px;

};

</style>

</head>

<body>

<img src="img/1.jpg" alt="" />

</body>

</html>

  • 如何使用腾讯朋友网圈子功能
  • 手机壳变黄怎么办
  • 点淘如何签到
  • 居然还有那么多人不知道艾斯有霸王色!
  • 王者荣耀钟馗新皮肤怎么获得
  • 热门搜索
    隐形纱窗怎么清洗 比亚迪g6质量怎么样 希利苏斯怎么去 什么植物可以净化空气 qq隐藏了怎么找出来 辽宁旅游景点大全介绍 公司规模怎么写 石家庄附近旅游景点 定期存款可以提前取出来吗 凉拌藕片