我有一个列表,我希望使用键向上/向下移动该列表,但它也会滚动浏览我的页面。我认为preventDefault是关于事件的,这会解决问题,但不会。
小提琴http://jsfiddle.net/mato75/wKJ26
<div ng-onkeyup="moveUp($event)" ng-onkeydown="moveDown($event)">
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
</div>
scope.moveUp = function (event) {
moveUp();
event.preventDefault();
}
scope.moveDown = function (event) {
moveDown();
event.preventDefault();
}
答案 0 :(得分:0)
好的想通了,你在对keyup和keydown处理程序的引用中有了这个词,你还需要div上的tabindex,这样才能获得焦点,事件可以从它传播http://plnkr.co/edit/dUSFZT2TfHIfY18GUDp0
HTML
<!DOCTYPE html>
<html>
<head>
<script data-require="angular.js@*" data-semver="1.2.14" src="http://code.angularjs.org/1.2.14/angular.js"></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body ng-app="myApp">
<h1>Hello Plunker!</h1>
<div ng-controller="MyCtrl">
<div tabindex=1 ng-keyup="moveUp($event)" ng-keydown="moveDown($event)">
<ul>
<li>One
</li>
<li>Two</li>
<li>Three</li>
</ul>
</div>
</div>
<div>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
Stuff<br>
</div>
</body>
</html>
JS
// Code goes here
angular.module("myApp", []).controller("MyCtrl", function($scope){
$scope.moveUp = function (event) {
event.preventDefault();
console.log("move up")
}
$scope.moveDown = function (event) {
event.preventDefault();
console.log("move down")
}
});
答案 1 :(得分:0)
以下是一个示例,http://jsfiddle.net/mato75/wKJ26/3/
angular.module('myApp', [])
.controller('MyCtrl', ['$scope', function ($scope) {
$scope.list = ['item1', 'item2', 'item3', 'item4', 'item5'];
$scope.selected = 'item2';
$scope.isSelected = function(item) {
return item === $scope.selected ? 'active' : '';
}
$scope.selectItem = function (item) {
$scope.selected = item;
}
$scope.keyDown = function (event) {
var indx = $scope.list.indexOf($scope.selected);
switch(event.keyCode) {
case 40:
var nIndx = indx === $scope.list.length - 1 ? 0 : indx + 1;
var item = $scope.list[nIndx];
$scope.selectItem(item);
event.preventDefault();
break;
case 38:
var nIndx = indx === 0 ? $scope.list.length - 1 : indx - 1;
var item = $scope.list[nIndx];
$scope.selectItem(item);
event.preventDefault();
break
}
}
}]);