最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do focus and blur bubble up the DOM when switching between children? - Stack Overflow

programmeradmin1浏览0评论

When switching focus between children of a <div>, I'd like to fire a function. (The children are <span>s, if that matters). I know I can handle this by binding the function to the blur event of each of the children, but I'll potentially be creating (and destroying) lots of child elements, and would like to avoid binding the function to the children themselves.

For many events, like click or mouseover, I know that the event will bubble up the DOM and fire the same event on my parent div, where I can catch it and handle it. I'm not sure how blur and focus events would bubble, though. It seems like the parent still has focus, since one of its children has focus, but javascript is a strange and beautiful creature.

Can I rely on blur/focus events bubbling up when changing between children of an element, or is there a better way of handling changing focus between the children?

When switching focus between children of a <div>, I'd like to fire a function. (The children are <span>s, if that matters). I know I can handle this by binding the function to the blur event of each of the children, but I'll potentially be creating (and destroying) lots of child elements, and would like to avoid binding the function to the children themselves.

For many events, like click or mouseover, I know that the event will bubble up the DOM and fire the same event on my parent div, where I can catch it and handle it. I'm not sure how blur and focus events would bubble, though. It seems like the parent still has focus, since one of its children has focus, but javascript is a strange and beautiful creature.

Can I rely on blur/focus events bubbling up when changing between children of an element, or is there a better way of handling changing focus between the children?

Share Improve this question asked Mar 3, 2014 at 20:14 ckerschckersch 7,6972 gold badges41 silver badges48 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 6

focus and blur do not have a bubbling phase - https://developer.mozilla/en-US/docs/Web/API/Element/focus_event

Instead, you can use focusin that has bubbling.

Bubbling should work fine with blur and focus

var myElem = document.getElementById("foo");
myElem.addEventListener('blur', function(evt) {
    var elem = evt.srcElement || evt.target;
    console.log("blur: " + elem.name);
}, true);
myElem.addEventListener('focus', function(evt) {
    var elem = evt.srcElement || evt.target;
    console.log("focus: " + elem.name);
}, true);

IE uses onfocusin and onfocusout instead.

http://jsfiddle/p6bAL/

发布评论

评论列表(0)

  1. 暂无评论