繁体   English   中英

使用上/下箭头通过AngularJS聚焦并选择列表值

[英]Using up/down arrow to focus and select list values with AngularJS

我有一个input元素,当它的内容更改时-填充了ul列表。 我能够专注于使用CSS的鼠标悬停。

问题:

1)如何使用向上/向下箭头键 聚焦 ul > li列表值?
2)如何使用Enter键 选择 ul > li值?

请参考http://jsfiddle.net/3etbtfwL/458/

您可以在input元素上使用ngKeydown指令来处理keydown事件,并检查按下了哪些 (在您的情况下为ngClass代码),并使用ngClass直观地表示当前集中的列表元素。 这是一个工作示例:

 var app = angular.module('httpApp', []) .controller('httpAppCtrlr', function ($scope) { $scope.focusedIndex = 0; $scope.Change = function (item) { $scope.items = $.grep($scope.list, function (v) { if (v.name === item) { return v.value; } }); $scope.focusedIndex = 0; }; $scope.selected = function (value) { $scope.selectedValue = value; }; $scope.list = [ { "name": "1", "value": "value1" }, { "name": "1", "value": "value2" }, { "name": "1", "value": "value3" }, { "name": "2", "value": "value4" }, { "name": "2", "value": "value5" } ]; $scope.handleKeyDown = function($event) { var keyCode = $event.keyCode; if (keyCode === 40) { // Down $event.preventDefault(); if ($scope.focusedIndex !== $scope.items.length - 1) { $scope.focusedIndex++; } } else if (keyCode === 38) { // Up $event.preventDefault(); if ($scope.focusedIndex !== 0) { $scope.focusedIndex--; } } else if (keyCode === 13 && $scope.focusedIndex >= 0) { // Enter $event.preventDefault(); $scope.selected($scope.list[$scope.focusedIndex].value); } }; }); 
 .outputLists { padding: 6px; display: block; cursor: pointer; outline: 0; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; } .outoutList { display: block; z-index: 99; width: 30%; position: absolute; top: 36px; margin: -1px 0 0; border: 1px solid #eee; border-top: 0; padding: 0; background: #eee; -webkit-border-radius: 0 0 5px 5px; } .outputLists.focus { background: #428bca; } 
 <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script> <div data-ng-app='httpApp' data-ng-controller='httpAppCtrlr'> <input type="text" ng-change="Change(item)" ng-model="item" placeholder="select" ng-keydown="handleKeyDown($event)"/> <ul class="outoutList" tabindex="0" ng-keydown="handleKeyDown($event)"> <li ng-repeat="item in items" data-item="true" data-index="0" class="outputLists" ng-click="selected(item.value)" ng-class="{'focus': focusedIndex == $index}" ng-mouseover="$parent.focusedIndex = $index"> {{item.value}} </li> </ul> <lable> Selected Value: {{selectedValue}}, Vocused index: {{focusedIndex}} </lable> </div> <script src="//code.jquery.com/jquery-1.10.2.js"></script> 

更新:要允许对列表元素进行键盘操作,可以将tabindex添加到ul并使用相同的ng-keydown事件。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM