Js控制滑轮左右滑动实例


今天弄了一个东西,页面本来是横向,所以底部有横向滚动条,竖着就没有滚动条了,现在要求是鼠标滑轮要左右滚动,这就需要写js代码来实现了,写这个的过程中遇到很大麻烦

ie 火狐 chrome 三个浏览器支持的函数完全不一样,真是疯啦。

这里有几个知识点说明一下
监控滑轮的事件
ie:onmousewheel
firfox:DOMMouseScroll
chrome:mousewheel
哎真是无语
滚动的返回值也是不一样的
firfox用detail 返回 +-3
其他的用wheelDelta 返回 +-120
有返回值判断滚动的方向

还有一般浏览器除了chrome判断页面的左移动用document.documentElement.scrollLeft
但是chrome浏览器要用document.body.scrollLeft

好了代码分享如下:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
</head>
 
<body>
<div id="test" style="width:3000px; height:500px; background:#666;"></div>
<script language="javascript">
 
var dbody=document.getElementById('test');
//ff用
objAddEvent(document,'DOMMouseScroll', function(e){return mouse_scroll(e);})
 
//非ff chrome 用
objAddEvent(document,'mousewheel', function(e){return mouse_scroll(e);})
 
//chrome用
objAddEvent(dbody,'mousewheel', function(e){return mouse_scroll(e);})
function mouse_scroll(e){
e=e || window.event;
var delD=e.wheelDelta?e.wheelDelta: -e.detail*40;//判断上下方向
var move_s=delD>0?-50:50;
document.documentElement.scrollLeft+=move_s; //非chrome浏览器用这个
//chrome浏览器用这个
if(document.documentElement.scrollLeft==0)document.body.scrollLeft+=move_s;
 
return false;
}
//这个是给对象增加监控方法的函数
function objAddEvent(oEle, sEventName, fnHandler)
{
if(oEle.attachEvent) oEle.attachEvent('on'+sEventName, fnHandler);
else oEle.addEventListener(sEventName, fnHandler, false);
}
 
 
</script>
</body>
</html>

这个代码其实有点问题就是在chrome浏览器下只有鼠标放到那个灰色内才能滑动,这个问题我一直没有解决掉,如果那个高手解决可以留言告诉我,谢谢了。


« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3