2014-12-03 87 views
1
$(document).on("keyup", function(e) { 
    var code = e.which; 
    var currentTabIndex = document.activeElement.tabIndex; 
    if (code == 40) { 
     alert(currentTabIndex); 
     //set tabIndex to currentIndex + 1; 
    } else if (code == 39) { 
     alert(currentTabIndex); 
     //set tabIndex to currentIndex + 1; 
    } 
    else if (code == 38) { 
     alert(currentTabIndex); 
     //set tabIndex to currentIndex - 1; 
    } 
    else if (code == 37) { 
     alert(currentTabIndex); 
     //set tabIndex to currentIndex - 1; 
    } 
}); 

請參閱FIDDLE進行演示。如何在keydown或keyup上爲給定的activeElement tabIndex設置tabIndex?

+0

你能描述你試圖達到的目標嗎? – Sampson 2014-12-03 01:14:18

+0

@JonathanSampson如果按下鍵盤按鈕,tabindex焦點應該是當前具有選項卡Index焦點的元素之前的元素,否則如果按鈕keydown是按下,tabindex焦點應該是具有選項卡的當前元素之後的元素Index index :) – bumbumpaw 2014-12-03 01:18:12

+0

因此,如果他們按下向上箭頭,請將第一個元素的「tabIndex」設置爲activeElement。如果他們按下向下箭頭,請使用大於activeElement的'tabIndex'來關注第一個元素? – Sampson 2014-12-03 01:20:28

回答

1

您可以使用.filter()選擇具有所需tabIndex,然後該元素使用.focus()像這樣:

$('*').filter(function() { 
    return this.tabIndex == currentTabIndex + 1; 
}).focus(); 

將焦點設置到任何元素,然後按向下箭頭在下面的演示:

DEMO

UPDATE

這裏是你將如何避免Tab鍵如果有源元件接受文本輸入,要麼按下左箭頭右箭頭下面是完整的代碼

$(document).on("keyup", function(e) { 
    var code = e.which, 
     elm = document.activeElement, //capture the current element for later 
     currentTabIndex = elm.tabIndex, 
     nextTabIndex = code == 40 || code == 39 ? currentTabIndex + 1 : 
    code == 38 || code == 37 ? currentTabIndex - 1 : null, //calculate next tab index 
     isHoriz = code == 39 || code == 37; //Left or right arrow pressed 
    $('[tabindex]').filter(function() { 
     if(!$(elm).is(':text,textarea') || !isHoriz) { //Exclude left/right arrow for text inputs 
      return this.tabIndex == nextTabIndex; 
     } 
    }) 
    .focus(); 
}); 

DEMO

+0

如果用戶在輸入字段上,我不希望tabIndexing只觸發正常的左右光標應該對輸入字段文本執行操作。 – bumbumpaw 2014-12-03 01:44:32

+0

優化您的選擇器,使其僅包含要定位的元素,例如,通過使用.not('input')... – PeterKA 2014-12-03 01:50:03

+0

爲此,如果活動元素是文本輸入並且用戶按下左或右箭頭。圍繞代碼的if語句將會執行。 – PeterKA 2014-12-03 02:04:49

1

我就可以說只是搶元素與下一首或上tabindex,並呼籲.focus()

$("[tabindex='" + (currentTabIndex + 1) + "']").focus(); 

$("[tabindex='" + (currentTabIndex - 1) + "']").focus(); 

Fiddle Here

編輯:

所以,你要停止功能,如果(「鍵按下」 ==「左箭頭」或「右箭頭」)和「輸入型」 ==「文本」?然後寫一個if語句來做這件事:

if ((code == 39 || code == 37) && $(e.target).attr('type') == "text") return; 

把這個放在函數的第二行。

+0

,如果用戶在輸入字段上,我不希望tabIndexing只觸發正常的左右光標應該對輸入字段文本執行操作。 – bumbumpaw 2014-12-03 01:41:55

+0

@bumbumpaw請參閱編輯和更新的小提琴。 – bowheart 2014-12-03 15:58:49