我在鼠标滚轮事件的 li 列表上创建了一个增量类函数,它在 Chrome 和 Safari 上运行良好,但在 Firefox 上该函数只能向下滚动,无法向后滚动。我该如何修复它? 这是我的实际代码:
var scrollable = $('ul li').length - 1,
count = 0,
allowTransition = true;
$('body').bind('wheel DOMMouseScroll', function(e) {
e.preventDefault();
if (allowTransition) {
allowTransition = false;
if (e.originalEvent.wheelDelta / 120 > 0) {
if (scrollable >= count && count > 0) {
$('.active').removeClass('active').prev().addClass('active');
count--;
} else {
allowTransition = true;
return false;
}
} else {
if (scrollable > count) {
$('.active').removeClass('active').next().addClass('active');
count++;
} else {
allowTransition = true;
return false;
}
}
setTimeout(function() {
allowTransition = true;
}, 1000);
}
})
body {
overflow: hidden;
}
ul li {
height: 20px;
width: 20px;
background: blue;
margin: 5px;
list-style: none
}
ul li.active {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="active"></li>
<li></li>
<li></li>
<li></li>
</ul>
最佳答案
Firefox 没有 wheelDelta
属性,因此该行
if (e.originalEvent.wheelDelta / 120 > 0) {`
line 将始终返回 false
,并且执行向上滚动的代码位于该 if
语句内。
In Firefox you can use the wheel event, which have the
deltaY
property (also standard in Chrome 31 [2013]).
对 if
语句的更改将解决您的问题:
if (e.originalEvent.wheelDelta / 120 > 0 || e.originalEvent.deltaY < 0) {
根据MDN ,deltaY
属性在最新版本的 chrome 和 firefox 以及 IE9 中兼容。
$(function(){
var scrollable = $('ul li').length - 1,
count = 0,
allowTransition = true;
$('body').bind('wheel', function(e) {
e.preventDefault();
if (allowTransition) {
allowTransition = false;
if (e.originalEvent.wheelDelta / 120 > 0 || e.originalEvent.deltaY < 0) {
if (scrollable >= count && count > 0) {
$('.active').removeClass('active').prev().addClass('active');
count--;
} else {
allowTransition = true;
return false;
}
} else {
if (scrollable > count) {
$('.active').removeClass('active').next().addClass('active');
count++;
} else {
allowTransition = true;
return false;
}
}
setTimeout(function() {
allowTransition = true;
}, 1000);
}
});
});
body {
overflow: hidden;
}
ul li {
height: 20px;
width: 20px;
background: blue;
margin: 5px;
list-style: none
}
ul li.active {
background: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
<li class="active"></li>
<li></li>
<li></li>
<li></li>
</ul>
关于javascript - 滚动功能在 Firefox 上不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38293055/