onblur 事件
定义和用法
onblur 事件发生在对象失去焦点时。
onblur 事件最常与表单验证代码一起使用(例如,当用户离开表单字段时)。
Tip: onblur 事件与 onfocus eventomgekeerd.
Tip: onblur 事件类似于 onfocusout event。主要区别在于 onblur 事件不会冒泡。因此,如果您想找出元素或其子元素是否失去焦点,可以使用 onfocusout 事件。但是,您可以通过使用 onblur 事件的 addEventListener() methodde useCapture parameter (optioneel) om dit te bereiken.
Example
Voer JavaScript uit wanneer de gebruiker het invoerveld verlaat:
<input type="text" onblur="myFunction()">
Er zijn meer TIY-exempelen onder de pagina.
语法
In HTML:
<element onblur="myScript">
In JavaScript:
object.onblur = function(){}myScript};
In JavaScript, use the addEventListener() method:
object.addEventListener("blur", myScript);
Note:Internet Explorer 8 and earlier versions do not support addEventListener() method.
Technical details
Bubbling: | Not supported |
---|---|
Cancelable: | Not supported |
Event type: | FocusEvent |
Supported HTML tags: | All HTML elements except: <base>, <bdo>, <br>, <head>, <html>, <iframe>, <meta>, <param>, <script>, <style> and <title> |
DOM version: | Level 2 Events |
Browser support
Event | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
onblur | Supported | Supported | Supported | Supported | Supported |
More examples
Example
Use "onblur" and "onfocus" events together:
<input type="text" onfocus="focusFunction()" onblur="blurFunction()">
Example
Event delegation: set the useCapture parameter of addEventListener() to true:
<form id="myForm"> <input type="text" id="myInput"> </form> <script> var x = document.getElementById("myForm"); x.addEventListener("focus", myFocusFunction, true); x.addEventListener("blur", myBlurFunction, true); function myFocusFunction() { document.getElementById("myInput").style.backgroundColor = "yellow"; } } function myBlurFunction() { } </script>
Example
Event delegation: using the focusin event (not supported by Firefox):
<form id="myForm"> <input type="text" id="myInput"> </form> <script> var x = document.getElementById("myForm"); x.addEventListener("focusin", myFocusFunction); x.addEventListener("focusout", myBlurFunction); function myFocusFunction() { document.getElementById("myInput").style.backgroundColor = "yellow"; } } function myBlurFunction() { } </script>