导航UI使用键盘 [英] Navigate the UI using keyboard
本文介绍了导航UI使用键盘的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
考虑下面的标记 -
Consider the following markup -
<ul id="list">
<li class="list-item" tabindex="0">test 1</li>
<li class="list-item" tabindex="1">test 2</li>
<li class="list-item" tabindex="2">test 3</li>
<li class="list-item" tabindex="3">test 4</li>
<li class="list-item" tabindex="4">test 5</li>
<li class="list-item" tabindex="5">test 6</li>
<li class="list-item" tabindex="6">test 7</li>
</ul>
和这片jQuery的code的 -
and this piece of jQuery code -
$(".list-item").bind({
keydown: function(e) {
var key = e.keyCode;
var target = $(e.currentTarget);
switch(key) {
case 38: // arrow up
target.prev().focus();
break;
case 40: // arrow down
target.next().focus();
break;
}
},
focusin: function(e) {
$(e.currentTarget).addClass("selected");
},
focusout: function(e) {
$(e.currentTarget).removeClass("selected");
}
});
$("li").first().focus();
我如何端口这code在角?我有这个迄今为止 -
How do I port this code in angular? I have this so far -
<li class="list-item" ng-repeat="item in items" tabindex="{{item.tabIndex}}">
{{item.name}}
</li>
我如何做角的结合?
How do I do the binding in angular?
推荐答案
我认为最好的方法是使用为重点的的tabIndex
定位元素。尝试这样的事情;
The best way I think is to use the tabindex
to locate elements for focus. Try something like this;
<li class="list-item" ng-repeat="item in items"
tabindex="{{item.tabIndex}}"
ng-class="item.selected"
ng-keydown="onKeydown(item, $event)" ng-focus="onFocus(item)">{{item.name}}
</li>
然后在您的控制器需要的KEYDOWN处理;
Then in your controller you want the Keydown handler;
var KeyCodes = {
BACKSPACE : 8,
TABKEY : 9,
RETURNKEY : 13,
ESCAPE : 27,
SPACEBAR : 32,
LEFTARROW : 37,
UPARROW : 38,
RIGHTARROW : 39,
DOWNARROW : 40,
};
$scope.onKeydown = function(item, $event) {
var e = $event;
var $target = $(e.target);
var nextTab;
switch (e.keyCode) {
case KeyCodes.ESCAPE:
$target.blur();
break;
case KeyCodes.UPARROW:
nextTab = - 1;
break;
case KeyCodes.RETURNKEY: e.preventDefault();
case KeyCodes.DOWNARROW:
nextTab = 1;
break;
}
if (nextTab != undefined) {
// do this outside the current $digest cycle
// focus the next element by tabindex
$timeout(() => $('[tabindex=' + (parseInt($target.attr("tabindex")) + nextTab) + ']').focus());
}
};
和一个保它简单的焦点处理器;
And a keep-it-simple focus handler;
$scope.onFocus = function(item, $event) {
// clear all other items
angular.forEach(items, function(item) {
item.selected = undefined;
});
// select this one
item.selected = "selected";
};
这是从我的头顶,万一它有助于任何人碰到这个线程来像我一样。
That's off the top of my head, in case it helps anyone coming across this thread like I did.
这篇关于导航UI使用键盘的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文