javascript - 一组单选按钮上的 onfocus 事件如何像单个控件一样工作?

标签 javascript html dom-events

考虑以下 HTML 和 JavaScript,它们也在此处:http://jsfiddle.net/5CetH/

<!DOCTYPE html>
<html>
<head>
    <title>Untitled Page</title>
<script type="text/javascript">
  var i=0;

  function _focus() {
    var message = document.getElementById("message");
    message.value = message.value + ++i + ". Focus\r\n";
  }

  function _blur() {
    var message = document.getElementById("message");
    message.value = message.value + ++i + ". Blur\r\n";
  }
  
</script>
</head>
<body>
<div style="background-color: Aqua; width: 100px; height: 50px" onfocus="_focus()" onblur="_blur()" tabindex="0">
  <input name="rb" type="radio" /><br />
  <input name="rb" type="radio" />
</div>
<br />
<textarea id="message" rows="15" cols="50"></textarea>
</body>
</html>

我想要的行为如下:

  • 当第一次点击 aqua div 区域的任何地方时(无论是否点击单选按钮),onfocus 事件应该被触发。
  • 当点击 aqua div 后,点击其他地方时,应该触发 onblur 事件。
  • 只要在 aqua div 区域内的任何地方点击一次以上,就不应触发任何事件,即使是从一个单选按钮点击到另一个单选按钮也是如此。

它似乎在 Chrome 中运行良好,但在 FireFox 8 或 IE 9 中运行不佳。

关于如何修复我的代码以使其正常工作有什么建议吗?

最佳答案

只能聚焦一些元素,例如<a><input> .对于其他元素,您必须自己实现。

// window.addFocusToElem(elem, callbacks) - returns id for removeFocusFromElem
// window.removeFocusByID(id)
// in IE <= 8 the blur events get fired in the wrong order!
// callbacks: { onFocus: function(e) {}, onBlur: function(e) {} } - both methods are optional
(function() {
    var addEvent, removeEvent;
    (function() {
        // sometimes in IE <= 8 the window.blur event isn't fired when the
        // window loses the focus but instead it is fired when the window gets
        // the focus back again. This requires some hacking - and because
        // 'fireEvent' in window === false it even requires some more hacking.
        var hasFocus = true;
        var queue = [];

        addEvent = function(node, evtType, callback) {
            if('addEventListener' in node)
                node.addEventListener(evtType, callback, false);
            else { // IE <= 8
                if(evtType === 'blur') {
                    queue.push(callback);
                }
                node.attachEvent('on' + evtType, callback);
            }
        }

        removeEvent = function(node, evtType, callback) {
            if('removeEventListener' in node)
                node.removeEventListener(evtType, callback, false);
            else { // IE <= 8
                if(evtType === 'blur') {
                    var length = queue.length;
                    while(length--) {
                        if(callback === queue[ length ]) {
                            queue.splice(length, 1);
                            break;
                        }
                    }
                }
                node.detachEvent('on' + evtType, callback);
            }
        }

        // IE <= 8
        if('documentMode' in document && document.documentMode <= 8) {
            setInterval(function() {
                if(!document.hasFocus() && hasFocus) {
                    hasFocus = false;
                    for(var o in queue) {
                        queue[ o ](document.createEventObject());
                    }
                }
            }, 100);
            addEvent(window, 'focus', function(e) {hasFocus = true;});
        }
    })();

    function doClick(node, evtType) {
        if('click' in node) { // most Browser (HTML-DOM)
            node.click();
        } else if('createEvent' in document) { // at least Chrome (16)
            var e = document.createEvent('MouseEvents');
            e.initEvent('click', true, true);
            node.dispatchEvent(e);
        } else {

        }
    }

    var id = 0;
    var queue = [];

    window.addFocusToElem = function addFocusToElem(elem, callbacks) {
        var _id = id++;
        var entry = queue[ _id ] = {
            elem: elem,
            onFocus: function(e) {
                removeEvent(entry.elem, 'click', entry.onFocus);
                addEvent(document, 'click', entry.onBlur);
                if('onFocus' in callbacks &&
                   typeof callbacks.onFocus === 'function') {
                    callbacks.onFocus(e);
                }
            },
            onBlur: function(e) {
                var node = 'target' in e ? e.target : e.srcElement;
                while(node) {
                    if(node === entry.elem) {
                        break;
                    }
                    node = node.parentNode;
                }
                if(!node) {
                    removeEvent(document, 'click', entry.onBlur);
                    addEvent(area, 'click', entry.onFocus);
                    if('onBlur' in callbacks &&
                       typeof callbacks.onBlur === 'function') {
                        callbacks.onBlur(e);
                    }
                }
            }
        };
        addEvent(elem, 'click', entry.onFocus);
        addEvent(window, 'blur', function(e) {
            doClick(elem.parentNode);
        });
        addEvent(document, 'keyup', function(e) {
            if(e.keyCode === 9) { // tab
                var node = 'target' in e ? e.target : e.srcElement;
                while(node) {
                    if(node === elem) {
                        doClick(elem);
                        break;
                    }
                    node = node.parentNode;
                }
                if(!node) {
                    doClick(elem.parentNode);
                }
            }
        });
        return _id;
    };
    window.removeFocusByID = function removeFocusByID(id) {
        if(id in queue) {
            var entry = queue[ id ];
            removeEvent(entry.elem, 'click', entry.onFocus);
            removeEvent(document, 'click', entry.onBlur);
            delete queue[ id ];
            return true;
        }
        return false;
    };
})();

用法:

<div style="background-color: Aqua; width: 100px; height: 50px" id='area'>
    <input name="rb" type="radio">Foo<br>
    <input name="rb" type="radio">Bar
</div>
<script type='text/javascript'>
var id = addFocusToElem(document.getElementById('area'), {
    onFocus: function(e) {
        // statements
    },
    onBlur: function(e) {
        // statements
    }
});
// removeFocusByID(id);
</script>

jsFiddle

关于javascript - 一组单选按钮上的 onfocus 事件如何像单个控件一样工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8579632/

相关文章:

html - 强制一个 div 更改同一父级内其他 div 的大小,以便可以看到第一个

javascript - 关闭 Firefox 时发送 XMLHttpRequest

javascript - 仅在 IE 上,表单 DOM id 返回 "is null or not an object"问题

javascript - 当子元素的 onclick 触发时,是否可以阻止浏览器跟踪链接?

javascript - 允许爬取需要 javascript 的网站的 Node 包

javascript - 在其他指令中重用 Angular Directive(指令)

html - 悬停时的图像与粘性标题重叠

javascript - 制作我的第一个 listObjects from Amazon S3 -- Classic "' Access-Control-Allow-Origin'"遇到

javascript - css 选择器或 xpath 选择器

html - Visual Studio Code - erb 和 html 一起