2011-10-22 35 views
0

本質上,我有一個可見的元素在任何時候,我用箭頭鍵來改變可見性,以兄弟元素。jQuery keydown()太急躁

Arrow left =顯示前一個元素爲可見的元素,然後隱藏下一個元素。

Arrow right =顯示下一個可見元素,然後隱藏前一個元素。

問題基本上是:快速按下箭頭鍵。

在我的jsfiddle當前可見的一個是4,如果我迅速按下Arrow rightArrow left我結束了在那裏,如果你一定要慢慢做(等待所有的動畫完成了)當你結束了4號3號就像你應該的。

http://jsfiddle.net/lollero/je2fZ/

我想要的是能夠按箭頭鍵儘快力所能及的,並最終顯示正確的號碼。

..這很奇怪,如果你先按左,然後右多次你最終顯示所有的數字......這也不是所希望的。

回答

1

使用的東西,以紀念當前元素,如:visible將匹配其藏元素荷蘭國際集團但尚未hidd 使用類here的演示。

+0

我喜歡那樣。這很簡單。在我認爲我非常聰明地使用':visible'作爲鉤子之後,並不是很喜歡增加額外的課程,但是......你不能總是贏。 – Joonas

+0

您可以使用'p:visible:not(:animated)'作爲選擇器,它不涉及任何類,但是它會忽略動畫過程中的任何按鍵。 – icktoofay

2

這肯定不會是乾淨的解決方案,但浮現在腦海的第一件事就是跟蹤所選元素的一個變量:

$('p:nth-child(4)').show(); 
var current = 3; 
$(document).keydown(function(e){ 
    if (e.keyCode == 37) { 
     $("p").stop(true, true).hide(500); 
     current = (current - 1 < 0) ? $("p").length - 1 : current - 1; 
     $("p").eq(current).stop(true, true).show(500); 
    } 
    else if (e.keyCode == 39) { 
     $("p").stop(true, true).hide(500); 
     current = (current + 1 == $("p").length) ? 0 : current + 1;  
     $("p").eq(current).stop(true, true).show(500); 
    } 
}); 

這裏有一個working example。請注意,此解決方案在到達開始/結束時循環並嘗試以相同方向繼續。我不知道這是否是你想要的,但它很容易修改。

:visible其他
1

我認爲最簡單的解決方案似乎是使用:animated選擇器來檢查是否存在動畫元素,如果存在,則返回false。或者說,來測試有沒有過程中的動畫,只有當沒有當前動畫,動畫的元素:

$('p:nth-child(4)').show(); 

$(document).keydown(function(e) { 
    if (e.keyCode == 37) { 
     if (!$('p:animated').length){ 
      $('p:visible').prev().stop(true, true).show(500).next().stop(true, true).hide(500); 
     } 
     return false; 
    } 
    else if (e.keyCode == 39) { 
     if (!$('p:animated').length){ 
      $('p:visible').next().stop(true, true).show(500).prev().stop(true, true).hide(500); 
     } 
     return false; 
    } 
}); 

JS Fiddle demo


被修改整理上面的代碼,以降低嵌套 if

$('p:nth-child(4)').show(); 

$(document).keydown(function(e) { 
    if (e.keyCode == 37 &&!$('p:animated').length){ 
     $('p:visible').prev().stop(true, true).show(500).next().stop(true, true).hide(500); 
     return false; 
    } 
    else if (e.keyCode == 39 && !$('p:animated').length){ 
     $('p:visible').next().stop(true, true).show(500).prev().stop(true, true).hide(500); 
     return false; 
    } 
}); 

JS Fiddle demo

參考文獻: