我有一些元素列表(每个元素是一行文本)。当你点击它时,它会改变颜色。在你点击一些项目后,如果你按"shift +箭头向上"上面的项目也被选中。如何实现它?我认为可以这样做:在ng-click函数中将焦点放在特定元素上,然后在ng-keydown函数中实现选择其他元素。但这似乎不起作用。
<div ng-repeat="elem in listCtrl.availableElements" class="list-elem" ng-class="{ 'selected' : listCtrl.availableElements[$index].selected }" ng-click="listCtrl.listHandler($event, listCtrl.availableElements[$index])" ng-keydown="$event.shiftKey && ($event.which == 38 || $event.which == 40) && listCtrl.listHandler($event, listCtrl.availableElements[$index])">
<div>
{{elem.text}}
</div>
</div>
首先是工作活塞
这是HTML
<div tabindex="{{$index}}" ng-keydown="moveCursor($event)" ng-repeat="elem in elements" ng-click="setCursor($index)">
<span ng-class="{ 'selected' : elements[$index].selected }">{{$index}} : {{elem.text}}</span>
</div>
需要添加 tabindex
以允许对元素进行关注。
在ng-click
上,我只是设置了一个光标。
$scope.setCursor = function(index){
var wasSelected = $scope.elements[index].selected;
$scope.unselectAll();
$scope.elements[index].selected = !wasSelected;
$scope.cursor = index;
$scope.initialCursor = index;
}
这个光标将是我选择的其他元素的枢轴。我需要保存initialCursor
,以知道在选择向下或向上时如何表现。
在ng-keydown
上,我只是自己处理事件并放置一些锁。
$scope.moveCursor = function(event){
if(event.shiftKey && event.which == 38){
if($scope.cursor > 0){
$scope.selectUp();
}
}else if(event.shiftKey && event.which == 40){
if($scope.cursor < $scope.elements.length-1){
$scope.selectDown();
}
}
}
selectUp()
和selectDown()
非常相似:
$scope.selectDown = function(){
//If the current cursor is ahead of the first click
if($scope.cursor < $scope.initialCursor){
$scope.elements[$scope.cursor].selected = !$scope.elements[$scope.cursor].selected;
$scope.cursor += 1;
}else{
$scope.cursor += 1;
$scope.elements[$scope.cursor].selected = !$scope.elements[$scope.cursor].selected;
}
}
$scope.selectUp = function(){
//If the current cursor is behind the first click
if($scope.cursor > $scope.initialCursor){
$scope.elements[$scope.cursor].selected = !$scope.elements[$scope.cursor].selected;
$scope.cursor -= 1;
}else{
$scope.cursor -= 1;
$scope.elements[$scope.cursor].selected = !$scope.elements[$scope.cursor].selected;
}
}
让我们看一下selectUp
函数。
我有两个行为要实现。
如果我在最初的点击和i selectUp
之前,我需要向上选择下一个项目。
如果我是在最初的点击和i selectUp
之后,我需要取消选中的最后一个项目。
希望有帮助。
如果你不喜欢我的实现,你可以直接使用"tabindex"