用鼠标滚轮选择列表元素

时间:2017-08-02 04:48:23

标签: jquery html-lists mousewheel

我想在dom听鼠标滚动时选择li,以便jquery只删除一个类并更改其类然后等待下一个滚动,然后选择下一个并执行相同操作。但我的代码是选择所有这些并立即更改类。

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');
        }
      });
    }
  })
}

2 个答案:

答案 0 :(得分:0)

要显示每个滚动一个元素,知道滚动事件每次旋转闪耀10次...
你必须以某种方式缓冲事件。

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>

答案 1 :(得分:-2)

在内部循环中,您正在控制任何没有显示类的'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');
            }});
    }
})
}