我有一叠Divs。我可以通过单击两个按钮(显示下一张或上一张卡片)来浏览它们。感谢dfsq到目前为止对我的帮助。但我试图与鼠标单击并排添加键盘操作。
当前单击“下一个”按钮显示下一个项目,“上一个”显示上一个项目(如果有)。 Plunker
我如何添加类似的东西
按键盘“向右箭头”与单击“下一步”按钮相同,按键盘“向左箭头”与单击上一个按钮相同。
我正在搜索如何执行此操作,但没有任何有效的方法。我看到了This,这是我的期望,但没有得到实现的方法。
任何解决方案/建议/示例将不胜感激
<div class="container">
<div class="col-md-2-4"
ng-class="{'card-hide': index > $index + 1}"
ng-repeat="card in cards"
ng-style="{left: 2 * $index + 'px', top: 2 * $index + 'px', 'z-index': (cards.length - $index)}">
<ul class="list-unstyled cs-tag-item-grp">
<li class="clearfix" ng-repeat="value in card.cardItem">
<div class="pull-left">
{{value.keys}}
</div>
</li>
</ul>
</div>
<div class="keys">
<button type="button" class="btn btn-next" ng-click="index = index < cards.length ? index + 1 : cards.length">Next</button>
<button type="button" class="btn btn-pre" ng-click="index = index > 1 ? index - 1 : 1">Previous</button>
{{index}}
</div>
</div>
最佳答案
将其添加到控制器或创建指令并将其添加到链接函数:
angular.element(document).bind("keydown", function(event){
var key = event.which;
switch(key) {
case 37:
$scope.index = $scope.index > 1 ? $scope.index - 1 : 1;
$scope.$apply();
break;
case 39:
$scope.index = $scope.index < $scope.cards.length ? $scope.index + 1 : $scope.cards.length
$scope.$apply();
break;
}
});
DEMO
指令代码:
app.directive("trackKeyDown", function () {
return {
restrict: "AEC",
link: function ($scope, element, attrs) {
angular.element(document).bind("keydown", function (event) {
var key = event.which;
switch (key) {
case 37:
$scope.index = $scope.index > 1 ? $scope.index - 1 : 1;
$scope.$apply();
break;
case 39:
$scope.index = $scope.index < $scope.cards.length ? $scope.index + 1 : $scope.cards.length
$scope.$apply();
break;
}
});
}
}
});
在您的HTML中:
<body ng-controller="MainCtrl" track-key-down>
DEMO with Directive
关于javascript - 难以执行键盘操作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/29611204/