javascript - 如何判断鼠标滚动方向是向上还是向下?

标签 javascript jquery

我正在尝试获取鼠标方向功能。我想知道如何检查鼠标滚动方向是顶部还是底部。

每次检查主体是否向上或向下方向滚动:

if(scroll top... ) {
    do something.....
}

if(scroll bottom... ) {
    do something.....
}

CSS:

body { 
    height:1400px; 
    margin:0; 
    padding:0; 
    position:relative; 
}
.get-direction-info-here {
    width:150px; 
    height:30px; 
    background:red; 
    display:block; 
    font-size:14px; 
    line-height:30px; 
    color:#fff; 
    position:fixed; 
    top:0;
}

HTML:

<div class="get-direction-info-here">
    Scroll direction: <!-- Scroll TOP --> / <!--Scroll Bottom-->
</div>

<div class="direction-info"> </div>

最佳答案

您可以使用mouse wheel events在 HTML5 中检测鼠标滚轮 Action 。向上/向下取决于增量是正(向上滚动)还是负(向下滚动)。

     window.onload = function() {

    	var directionInfo = document.getElementById("directionInfo");
    	
    	if (directionInfo.addEventListener) {
    		directionInfo.addEventListener("mousewheel", MouseWheelHandler, false);
    		directionInfo.addEventListener("DOMMouseScroll", MouseWheelHandler, false);
    	}
    	else directionInfo.attachEvent("onmousewheel", MouseWheelHandler);
    	
    	function MouseWheelHandler(e) {
    
    		// cross-browser wheel delta
    		var e = window.event || e;
    		var delta = Math.max(-1, Math.min(1, (e.wheelDelta || -e.detail)));
    		if(delta > 0)
              directionInfo.innerText = 'Up';
            else
              directionInfo.innerText = 'Down';
    		return false;
    	}
    
    }
.direction-info {
  width:100px;
  height:100px;
  border:1px solid green;
  }
<div id="directionInfo" class="direction-info"> </div>

关于javascript - 如何判断鼠标滚动方向是向上还是向下?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33846509/

相关文章:

javascript - 无法使用 PHP 从 CollegeBoard 获取内容

jquery.append 不适用于具有 id 的 div,但适用于 body?

javascript - 使用循环设置 mousedown 函数

javascript - 导出为 Three.js 的 Json 几何格式

javascript - jQuery - 选择值等于的元素

jquery - 单击模式中的按钮时,尝试更改启动模式的按钮的属性

javascript - 通过 javascript 临时更改 css

javascript - 在 Material-UI TextField 中,当输入模糊时,如何防止标签落在装饰后面?

javascript - 为第三方网站提供动态内容 'drop in' 小部件的最佳实践?

javascript - 覆盖 API CSS REACT