Html Div - onblur 功能
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18504139/
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
Div - onblur function
提问by user2357770
I want to call an onblur
on div
. Not sure how to get it done.
我想打电话onblur
给div
。不知道如何完成。
Tried this:
试过这个:
div onblur="javascript:callme()"
but it didn't work
但它没有用
回答by Strelok
For blur
event to fire on an element, the element needs to receive focus first. But <div>
elements do not receive focus by default.
要blur
在元素上触发事件,该元素需要首先获得焦点。但是<div>
默认情况下元素不会获得焦点。
You can add tabindex="0"
or contentEditable
to your div so it will receive focus.
您可以将tabindex="0"
或添加contentEditable
到您的 div 中,以便它获得焦点。
See it in action: http://jsfiddle.net/t25rm/
看到它在行动:http: //jsfiddle.net/t25rm/
回答by Quentin
The blur event fires when focus is lost. By default, a div element cannot have the focus in the first place so it can'tbe lost.
失去焦点时会触发模糊事件。默认情况下,div 元素不能首先获得焦点,因此它不会丢失。
If you set tabindex
on a div, then it can gain the focus, but you should almost always be using a more appropriate element (such as a button) when you think about making interactive controls.
如果你tabindex
在 div 上设置,那么它可以获得焦点,但是当你考虑制作交互式控件时,你几乎总是应该使用更合适的元素(例如按钮)。
<!-- Not recommended. See above -->
<div tabindex="1" onblur="callme()"> content </div>
回答by Shadow
If you give the div a tabindex attribute, it will be able to accept focus:
如果给 div 一个 tabindex 属性,它将能够接受焦点:
<div id="yourdivid" tabindex="0">content</div>
then attach focus and blur event handlers For example:
然后附加焦点和模糊事件处理程序例如:
document.getElementById("yourdivid").onfocus = function() {
alert('focused');
}
document.getElementById("yourdivid").onblur = function() {
alert('blur');
}