我正在捕捉这样的按键:
<div class="contentView"
ng-keypress="phs.keyEnter($event)">
keyEnter = ($event): void => {
var a = $event;
如何制作它以便单击一个键将光标移动到输入字段:
<input ng-change="phs.englishChange();"
ng-model="phs.english"
ng-model-options="{ debounce: 750 }"
style="width:6rem;"
type="text" />
答案 0 :(得分:6)
我认为directive
可以帮助我们为您的问题提供更通用且可重复使用的解决方案,因为它是将指定行为附加到input
元素的最佳位置。所以这是一个自定义doOnKeypress
指令,它接受一个键(doOnKeypress
)和一个可选的回调(acceptOn
)来检查被激活的keypress
event的目标和一个回调({ {1}})如果满足所有条件,将被解雇。
在下面的示例中,只要按下 a 键盘按钮,onKeypress
就会聚焦。我留下了评论,因此您可以根据自己的需要进行修改(希望总体思路清晰):
input
&#13;
angular.module("app", [])
.controller("TestController", ["$scope", function ($scope) {
$scope.acceptOn = function (target, element) {
console.log(target); // you can make any checks for target by passing this into a directive
return element[0] !== target[0]; //target is not the same input element
};
$scope.focusOn = function (element) {
element[0].focus(); // or whatever you want with element
};
}]).directive('doOnKeypress', ['$document', function ($document) {
return {
restrict: 'A',
scope: {
doOnKeypress: '@',
acceptOn: '&?',
onKeypress: '&'
},
link: function postLink(scope, element) {
function keypress(e) {
var target = angular.element(e.target);
var targetIsAcceptable = angular.isFunction(scope.acceptOn) ? scope.acceptOn({
target: target,
element: element
}) : true; // add the condition to test the target
var specialKeyPressed = e.shiftKey || e.ctrlKey || e.altKey || e.metaKey; // in case you need to check any special keys
if (targetIsAcceptable && !specialKeyPressed) {
var keyCode = e.which || e.keyCode;
var key = String.fromCharCode(keyCode);
if ("*" === scope.doOnKeypress || key.toLowerCase() === scope.doOnKeypress.toLowerCase()) { // any check before focusing (lets say * - is any key)
e.preventDefault(); // prevent from typing into the input
scope.onKeypress({element: element});
}
}
}
$document.on('keypress', keypress);
scope.$on('$destroy', function () {
$document.off('keypress', keypress);
});
}
};
}]);
&#13;
UPDATE:为<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.6.7/angular.min.js"></script>
<body ng-app="app" class="">
<div ng-controller="TestController" class='listen-to-keypress'>
TestController
<br/>
<div>
<input ng-change="phs.englishChange();"
ng-model="phs.english"
ng-model-options="{ debounce: 750 }"
style="width:6rem;"
do-on-keypress='A'
accept-on='acceptOn(target, element)'
on-keypress='focusOn(element)'
type="text" />
</div>
</div>
</body>
回调添加了element
参数,以便将目标与同一元素进行比较,因为我们希望让用户输入此{{1}在我们的例子中。
答案 1 :(得分:0)
<强> HTML 强>
<input value="_sample input value" ng-click="getCur_Pos($e)" ng-keyup="getCur_Pos($e)"/>
<div> Cursor Pos : <b ng-bind="curPos_Val"></b></div>
<强> SCRIPT 强>
$scope.getCur_Pos = function($e) {
$scope.doCar_Position($e.target);
};
$scope.doCar_Position = function(o_Fld) {
var _Crt_Pos = 0;
if (o_Fld.selectionStart || o_Fld.selectionStart == '0')
_Crt_Pos = o_Fld.selectionStart;
// Return results
$scope.curPos_Val = _Crt_Pos;
};