今天看了一篇关于使用css3方法实现整屏滚动效果的博客,发现里面用到了监听滚轮事件的js代码,于是翻了翻资料,进行了一下学习与总结:
下面是实现整屏切换的代码:
<!DOCTYPE html>
<html>
<head lang="ch">
<meta charset="UTF-8">
<meta name=”viewport” content="width=device-width, user-scalable=no, initial-scale=1.0">
<title></title>
<style>
body, html{
padding: 0;
margin: 0;
}
body, html {
height: 100%;
overflow: hidden;
}
#container, .section {
height: 100%;
}
.section {
background-color: #000;
background-size: cover;
background-position: 50% 50%;
}
#section0 {
background-color: #83af9b;
}
#section1 {
background-color: #764d39;
}
#section2 {
background-color: #ff9000;
}
#section3 {
background-color: #380d31;
}
</style>
</head>
<body>
<div id="container">
<div class="section" id="section0"></div>
<div class="section" id="section1"></div>
<div class="section" id="section2"></div>
<div class="section" id="section3"></div>
</div>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
var curIndex = 0;
var container = $("#container");
var sumCount = $(".section").length;
var $window = $(window);
var duration = 500;
//时间控制
var aniTime = 0;
var scrollFunc = function (e) {
//如果动画还没执行完,则return
if(new Date().getTime() < aniTime + duration){
return;
}
e = e || window.event;
var t = 0;
t=(e.wheelDelta)?e.wheelDelta/120:-(e.detail||0)/3;//兼容性处理
if (t > 0 && curIndex > 0) {
//上滚动
alert(t);
movePrev();
} else if (t < 0 && curIndex < sumCount - 1) {
//下滚动
alert(t);
moveNext();
}
};
function moveNext(){
//获取动画开始时的时间
aniTime = new Date().getTime();
container.css("transform", "translate3D(0, -" + (++curIndex) * $window.height() + "px, 0)");
}
function movePrev(){
//获取动画开始时的时间
aniTime = new Date().getTime();
container.css("transform", "translate3D(0, -" + (--curIndex) * $window.height() + "px, 0)");
}
function init(){
/*注册事件*/
if (document.addEventListener) {
document.addEventListener('DOMMouseScroll', scrollFunc, false);
}//ff
window.onmousewheel = document.onmousewheel = scrollFunc;//IE/Opera/Chrome
container.css({
"transition": "all 0.5s",
"-moz-transition": "all 0.5s",
"-webkit-transition": "all 0.5s"
});
}
init();
</script>
</body>
</html>
很明显我们发现滚轮事件存在浏览器兼容问题:
滚轮事件的兼容性差异有些不拘一格,不是以往的IE8-派和其他派,而是FireFox派和其他派。
包括IE6在内的浏览器是使用onmousewheel
,而FireFox浏览器一个人使用DOMMouseScroll
. 经自己测试,即使现在FireFox 19下,也是不识onmousewheel
。
根据自己的测试,在我的win7系统下,无论IE7, IE10, Opera12,或者是safari5.1,每次往下滚动event.wheelDelta
值都是-120,向上则是120
.
对于FireFox浏览器(Opera浏览器也有),判断鼠标滚动方向的属性为event.detail
, 向下滚动值为3,向上则是-3
.
需要注意的是,FireFox浏览器的方向判断的数值的正负与其他浏览器是相反的。FireFox浏览器向下滚动是正值,而其他浏览器是负值。
于是我在代码中使用了下面一句代码来实现兼容性处理:
t=(e.wheelDelta)?e.wheelDelta/120:-(e.detail||0)/3;//兼容性处理