2017-08-02 98 views
0

我正在尋找選擇的時候,聽聽鼠標滾輪,以便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'); 
     } 
     }); 
    } 
    }) 
} 

回答

0

揭示每次滾動一個元素,知道滾動事件觸發像每一個旋轉10次...
你必須緩衝以某種方式的事件。

A setTimeout()可以與標誌結合使用。
查看代碼中的註釋以獲取詳細信息。應提供downvote的

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>

+0

謝謝我在這個問題上花了這麼多,所以無法弄清楚解決方案會是那麼簡單謝謝! – mfarhan

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

原因。 –

+1

如果你向你的代碼添加一個解釋,這將有助於解釋爲什麼這會回答問題。只是發佈與問題中的示例幾乎完全相同的代碼,可能不足以說服人們這個答案是正確的。 –

+0

而你剛剛發佈了與OP完全相同的代碼......那不可能是答案。 –