在我上一个问题的答案中,Textarea突出重点,我发现了一个替代onfocus和onblur.这些是onfocusin和onfocusout.
我的问题是,两者之间的行为有何不同?
这个小提琴表明两者看起来都是一样的:http://jsfiddle.net/spedwards/pQLAM/
focus并且blur事件不会冒泡,因此事件委派对于这些事件是不可能的.
focusin和focusout气泡到父元素,并可以委派.
否则,他们是相同的,但focusin并focusout没有任何标准的一部分,但其实都是专有的IE事件,后来被其他一些浏览器采用,但它们不支持跨浏览器.
例
<div id="test">
<input type="text" />
</div>
Run Code Online (Sandbox Code Playgroud)
与js
var div = document.getElementById('test');
div.addEventListener('focus', handler, false); // does not work, focus does not bubble
div.addEventListener('focusin', handler, false); // works when input is focused, as the event bubbles
Run Code Online (Sandbox Code Playgroud)
onfocus():当输入字段获得焦点时触发。主要与输入、选择和标签一起使用。
onfocusin():onfocus 事件与 onfocusin 事件类似。主要区别在于 onfocus 事件不会冒泡。因此,如果你想知道一个元素或其子元素是否获得 focus(),你可以使用 onfocusin 事件。但是,您可以通过使用 onfocus 事件的 addEventListener() 方法的可选 useCapture 参数来实现此目的。另外,firefox 不支持 onfocusin()。
下面的代码是一个示例,其中选择了表单,但事件委托给作为表单子项的输入元素。如果用“focus()”替换,则不会发生同样的情况。
<!DOCTYPE html>
<html>
<body>
<p>When you enter the input field (child of FORM), a function is triggered which sets the background color to yellow. When you leave the input field, a function is triggered which removes the background color.</p>
<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() {
document.getElementById("myInput").style.backgroundColor = "";
}
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
onblur():当用户离开输入字段或失去焦点时。
onfocusout:onblur 事件与 onfocusout 事件类似。主要区别在于 onblur 事件不会冒泡,即不会委托给子元素。因此,如果您想知道某个元素或其子元素是否失去焦点,可以使用 onfocusout 事件。但是,您可以通过使用 onblur 事件的 addEventListener() 方法的可选 useCapture 参数来实现此目的。此外,firefox 不支持 onfocusout()。