[英]How to detect if user has left the input field?
Suppose I have an input field,假设我有一个输入字段,
<input id="city" placeholder="city">
and I want to detect whenever user leaves this field.我想检测用户何时离开此字段。 How can I do so?
我怎么能这样做?
var element = document.getElementById("ELEMENT_ID");
element.addEventListener("blur", function() { ... your code here ...});
$("#ELEMENT_ID").on("blur", function() { ... your code here ...});
If, by any chance, you're implementing those self-emptying fields with predefined text, use placeholder
attribute .如果您在任何情况下使用预定义文本实现这些自清空字段,请使用
placeholder
属性。 If you're changing style based on focus, use:focus
CSS selector .如果您要根据焦点更改样式,请使用
:focus
CSS 选择器。 Also, change
event is emitted if user leaves the field and changed it's contents.此外,如果用户离开该字段并更改其内容,则会发出
change
事件。
When an element loses focus, the onblur
event is fired.当元素失去焦点时,会触发
onblur
事件。
var elem = document.getElementById('city');
elem.addEventListener("blur", function( event ) {
console.log('Elvis has left the city (input)!');
}, true);
https://developer.mozilla.org/en-US/docs/Web/Events/blur https://developer.mozilla.org/en-US/docs/Web/Events/blur
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.