js 鼠标滑轮滚动事件

  • Post author:
  • Post category:其他


鼠标滚动事件

	**非火狐**
	.onmousewheel='操作'
	鼠标方向
		event.wheelDelta;   //在火狐下无值
			鼠标往上滚 ,120   //按其整倍数设置滚动快慢
			鼠标往下滚。-120
	
	**火狐**
		dom2事件
			.addEventListener('DOMMouseScroll',function(){
				.innerHTML=event.detail;
			},false)
		鼠标方向
			event.detail
			 -3,滚动向上
			 3,滚动向下
			 
兼容性写法
	见程序

代码示例

<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.box{
				height:200px;
				width:200px;
				background-color: orange;
			}
		</style>
	</head>
	<body>
		
		<div class="box">
			
		</div>
		<script>
			var box=document.querySelector(".box");
/*			box.onmousewheel=function(event){
				var event=event||window.event;
				
				box.innerHTML=event.wheelDelta;
			}
			
			try{
				box.addEventListener("DOMMouseScroll",function(event){
					var event=event||window.event;
					
					console.log(event.detail);
				},false);
			}catch(error)
			{
				console.log(error);
			}*/
			
			function mouseScroll()
			{
				var event=event||window.event;
				
				var direction=0;
				if(event.wheelDelta)
				{
					direction=event.wheelDelta>0 ? 1:-1;
					console.log(direction);
				}else{
					//火狐
					direction=event.detail<0 ?1:-1;
					console.log(direction);
				}
				
				
			}
			
			box.onmousewheel=mouseScroll;
			try{   //这么写原因是,ie8以下dom2会报错
				box.addEventListener('DOMMouseScroll',mouseScroll,false);
				
			}catch(error)
			{
				console.log("a");
			}
			
		
		</script>
	</body>
</html>



版权声明:本文为weixin_43294560原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。