滚动功能在 Firefox 上不起作用

Scroll function doesn't work on firefox

我在鼠标滚轮事件的 li 列表上增加了一个 class 函数,它在 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) {`

行将始终 return 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) {

根据 MDNdeltaY 属性 与最新版本的 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>