使用鼠标滚轮选择列表元素

selecting list element with mousewheel scroll

当 dom 听鼠标滚轮时,我一直在寻找 select li 以便 jquery 仅删除一个 class 并更改其 class然后等待下一个滚动,然后 select 下一个并执行相同的操作。但是我的代码是 selecting 所有这些并立即更改 classes。

function scrollMe (){
  $('.header').on('mousewheel', function(e){
    e.preventDefault();
    var scrolled = e.originalEvent.wheelDelta;
    if(scrolled < 0){
      $('li').each(function(i){
        if($('li').hasClass('no-show')){
          $('li').removeClass('no-show').addClass('is-visible');
        }
      });
    }
  })
}

在循环内部,您正在控制任何未显示 class 的 'li' 元素。通过进行以下更改,它将查找每个 'li' 元素并为每个元素进行处理。

function scrollMe (){
$('.header').on('mousewheel', function(e){
    e.preventDefault();
    var scrolled = e.originalEvent.wheelDelta;
    if(scrolled < 0){
        $('li').each(function(i){
            if($(this).hasClass('no-show')){
            $(this).removeClass('no-show').addClass('is-visible');
            }});
    }
})
}

要在每次滚动时显示一个元素,知道滚动事件会在每次旋转时触发 10 次...
您必须以某种方式缓冲事件。

A setTimeout() 可以与标志一起使用。
详情看代码中的注释。

var timer;

// This is a flag to know if we scrolled.
var scrolling=false;

$('.header').on('mousewheel', function(e){

  // Get the scrolling direction
  var scrolled = e.originalEvent.wheelDelta;

  if(scrolled < 0 && !scrolling){ // if scroll down for the first time for at least 1 second.

    // Show the first hidden li found
    $('li.no-show').first().removeClass('no-show').addClass('is-visible');
  }

  // As long as user scrolls, 
  // he clears the timer
  clearTimeout(timer);

  // and sets a new one (delaying more...).
  timer = setTimeout(function(){

    // After at least 1 second not scrolling, reset the flag.
    scrolling=false;
  },1000);

  // Set the flag to know we just scrolled.
  scrolling=true;

});
.header{
  height:300px;
  background-color:#ddd;
  overflow-y:scroll;
}
.no-show{
  display:none;
}
.is-visible{
  display:list-item;
  color:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="header">
  <ul>
    <li>1</li>
    <li class="no-show">2</li>
    <li>3</li>
    <li class="no-show">4</li>
    <li>5</li>
    <li class="no-show">6</li>
    <li>7</li>
    <li class="no-show">8</li>
    <li>9</li>
    <li class="no-show">10</li>
  </ul>
</div>