考虑以下标记-
<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代码-
$(".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();
我该如何以 Angular 移植此代码?到目前为止,我有这个-
<li class="list-item" ng-repeat="item in items" tabindex="{{item.tabIndex}}">
{{item.name}}
</li>
我该如何成 Angular 地装订?
最佳答案
我认为最好的方法是使用tabindex
定位要聚焦的元素。尝试这样的事情;
<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>
然后,在您的 Controller 中,您需要Keydown处理程序;
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());
}
};
还有一个保持简单的焦点处理程序;
$scope.onFocus = function(item, $event) {
// clear all other items
angular.forEach(items, function(item) {
item.selected = undefined;
});
// select this one
item.selected = "selected";
};
万一它可以像我一样帮助任何遇到此问题的人,这都是我的首要任务。
关于angularjs - 使用键盘导航UI,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/16859970/