javascript 检查输入是否有焦点
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23157139/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if input has focus
提问by Spearfisher
I have an input with a minimum number of characters required. When a user start typing something and then switch to another field without reaching the minimum number of characters required, I want to change the class of a text to turn it to red.
我有一个需要最少字符数的输入。当用户开始输入内容然后切换到另一个字段而没有达到所需的最少字符数时,我想更改文本的类别以将其变为红色。
I have tried using this code to detect when the focus change but it is not working:
我曾尝试使用此代码来检测焦点何时发生变化,但它不起作用:
$scope.$watch(function(){
return $('#job_desc').is(':active');
}, function(){
console.log('test');
})
what is the problem?
问题是什么?
Many thanks
非常感谢
回答by zszep
If you are using angularjs 1.2 you have two directives to help you to watch if a field has focus: ng-focus and ng-blur. If not, it's quite simple to implement your own directives. The code (plunker):
如果你使用的是 angularjs 1.2,你有两个指令可以帮助你观察一个字段是否有焦点:ng-focus 和 ng-blur。如果没有,实现自己的指令非常简单。代码(plunker):
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<script>document.write('<base href="' + document.location + '" />');</script>
<link rel="stylesheet" href="style.css" />
<script data-require="jquery" data-semver="2.0.3" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
<script data-require="[email protected]" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js" data-semver="1.2.16"></script>
<script src="app.js"></script>
</head>
<body ng-controller="MainCtrl">
<p>Hello {{name}}!</p>
<form>
<input ng-model="name" id="name" ng-focus="focused()" ng-blur="blurred()">
<input ng-model="name2">
</form>
</body>
</html>
and the javascript
和 javascript
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope) {
$scope.name = 'World';
$scope.focused = function() {
console.log("got focus");
}
$scope.blurred = function() {
console.log("lost focus");
}
});
If on the other hand, you just want validation, look into form validation in angularjs, something like myForm.myInput.$valid. Angularjs sets the ng-valid and ng-invalid classes accordingly.
另一方面,如果您只想验证,请查看 angularjs 中的表单验证,例如 myForm.myInput.$valid。Angularjs 相应地设置 ng-valid 和 ng-invalid 类。
回答by Samuel Ayvazyan
You can listen by specific selector also, like this.
您也可以按特定选择器收听,就像这样。
function listenForFocus() {
var el = angular.element( document.querySelectorAll( 'input, select' ) );
for (var i = 0; i < el.length; i++) {
var element = angular.element(el[i]);
element.bind('blur', function (e) {
console.log('blur');
});
element.bind('focus', function (e) {
console.log('focus');
});
}
}