Js控制滑轮左右滑动实例
今天弄了一个东西,页面本来是横向,所以底部有横向滚动条,竖着就没有滚动条了,现在要求是鼠标滑轮要左右滚动,这就需要写js代码来实现了,写这个的过程中遇到很大麻烦
ie火狐chrome三个浏览器支持的函数完全不一样,真是疯啦。
这里有几个知识点说明一下
监控滑轮的事件
ie:onmousewheel
firfox:DOMMouseScroll
chrome:mousewheel
哎真是无语
滚动的返回值也是不一样的
firfox用detail返回+-3
其他的用wheelDelta返回+-120
有返回值判断滚动的方向
还有一般浏览器除了chrome判断页面的左移动用document.documentElement.scrollLeft
但是chrome浏览器要用document.body.scrollLeft
好了代码分享如下:
<!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<htmlxmlns="http://www.w3.org/1999/xhtml">
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
<title>无标题文档</title>
</head>
<body>
<divid="test"style="width:3000px;height:500px;background:#666;"></div>
<scriptlanguage="javascript">
vardbody=document.getElementById('test');
//ff用
objAddEvent(document,'DOMMouseScroll',function(e){returnmouse_scroll(e);})
//非ffchrome用
objAddEvent(document,'mousewheel',function(e){returnmouse_scroll(e);})
//chrome用
objAddEvent(dbody,'mousewheel',function(e){returnmouse_scroll(e);})
functionmouse_scroll(e){
e=e||window.event;
vardelD=e.wheelDelta?e.wheelDelta:-e.detail*40;//判断上下方向
varmove_s=delD>0?-50:50;
document.documentElement.scrollLeft+=move_s;//非chrome浏览器用这个
//chrome浏览器用这个
if(document.documentElement.scrollLeft==0)document.body.scrollLeft+=move_s;
returnfalse;
}
//这个是给对象增加监控方法的函数
functionobjAddEvent(oEle,sEventName,fnHandler)
{
if(oEle.attachEvent)oEle.attachEvent('on'+sEventName,fnHandler);
elseoEle.addEventListener(sEventName,fnHandler,false);
}
</script>
</body>
</html>
这个代码其实有点问题就是在chrome浏览器下只有鼠标放到那个灰色内才能滑动,这个问题我一直没有解决掉,如果那个高手解决可以留言告诉我,谢谢了。