考虑以下标记 -
<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>
Run Code Online (Sandbox Code Playgroud)
和这段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();
Run Code Online (Sandbox Code Playgroud)
如何以角度方式移植此代码?到目前为止我有这个 -
<li class="list-item" ng-repeat="item in items" tabindex="{{item.tabIndex}}">
{{item.name}}
</li>
Run Code Online (Sandbox Code Playgroud)
如何以角度进行装订?
cir*_*rus 11
我认为最好的方法是使用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>
Run Code Online (Sandbox Code Playgroud)
然后在你的控制器中你需要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());
}
};
Run Code Online (Sandbox Code Playgroud)
还有一个简单易用的焦点处理程序;
$scope.onFocus = function(item, $event) {
// clear all other items
angular.forEach(items, function(item) {
item.selected = undefined;
});
// select this one
item.selected = "selected";
};
Run Code Online (Sandbox Code Playgroud)
这是我的头脑,如果它像我一样帮助任何人遇到这个线程.
您还可以创建一个如下所示的角度指令:
claimApp.directive('keyNavigation', function ($timeout) {
return function (scope, element, attrs) {
element.bind("keydown keypress", function (event) {
if (event.which === 38) {
var target = $(event.target).prev();
$(target).trigger('focus');
}
if (event.which === 40) {
var target = $(event.target).next();
$(target).trigger('focus');
}
});
};
});
Run Code Online (Sandbox Code Playgroud)
然后在HTML中使用它,如下所示:
<li class="list-item" ng-repeat="item in items" key-navigation>
{{item.name}}
</li>
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
27250 次 |
| 最近记录: |