我有一个文本框,我想使用功能键(f1-f12)作为快捷键。例如,每次我按 f4 时,我都想让元素聚焦。
<input type="text" shortcutkey="f14">
快捷键只是一个例子。
类似这样的东西。
另外,浏览器使用这些功能键,有没有办法通过代码禁用它们的键。
最佳答案
您可以构建目录,以便在其 link
函数中监听文档上的 keyup
事件,如果键是属性的值,则聚焦该元素。像这样:
angular.module('app', [])
.controller('ctrl', function() {})
.directive('shortcutkey', function() {
return {
scope: {
shortcutkey: '@',
},
link: function(scope, element) {
function onKeyUp(e) {
if (e.code.toLowerCase() === scope.shortcutkey.toLowerCase()) {
element[0].focus();
}
}
document.addEventListener('keyup', onKeyUp);
/* because we added a listener we want to remove it once the element - the directive's "owner" has been removed from the DOM, to avoid unnecessary listeners
https://stackoverflow.com/a/17203143/863110
*/
scope.$on('$destroy', function() {
document.removeEventListener('keyup', onKeyUp);
});
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="app" ng-controller="ctrl">
<input type="text" shortcutkey="f4">
</div>
https://jsbin.com/xixovag/3/edit?html,js,output
不过,我认为您无法阻止浏览器对该事件采取行动。
正如@georgeawg提到的,ng-
前缀是Angular指令的约定,例如ng-show
和ng-hide
。虽然这可行,但阅读代码的人会认为该指令来自 Angular。
关于javascript - Angularjs 使用功能键作为快捷键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57457257/