2

似乎使用 contenteditable,无论您在页面上单击何处,您都会获得焦点。

如何仅在单击其自身的元素而不是在元素外部时才获得焦点?

见演示:http: //jsbin.com/iTEkUKa/1/edit

尝试在任何框外单击,它仍然会导致焦点,这就是问题所在。

4

1 回答 1

2

使用这个脚本:

它的工作原理很容易解释如下:

在 contenteditable-element 外部单击时,获取将被聚焦的 contenteditable-element。
如果在接下来的焦点事件中,此元素获得焦点,则将其移除。

https://gist.github.com/nuxodin/b02064610abf93dab8c6

if (/AppleWebKit\/([\d.]+)/.exec(navigator.userAgent)) {
    document.addEventListener('DOMContentLoaded', function(){
        var fixEl = document.createElement('input');
        fixEl.style.cssText = 'width:1px;height:1px;border:none;margin:0;padding:0; position:fixed; top:0; left:0';
        fixEl.tabIndex = -1;

        var shouldNotFocus = null;

        function checkMouseEvent(e){
            if (e.target.isContentEditable) return;
            var range = document.caretRangeFromPoint(e.clientX, e.clientY);
            var wouldFocus = getContentEditableRoot(range.commonAncestorContainer);
            if (!wouldFocus || wouldFocus.contains(e.target)) return;
            shouldNotFocus = wouldFocus;
            setTimeout(function(){
                shouldNotFocus = null;
            });
            if (e.type === 'mousedown') {
                document.addEventListener('mousemove', checkMouseEvent, false);
            }
        }
        document.addEventListener('mousedown', checkMouseEvent, false);
        document.addEventListener('mouseup', function(){
                document.removeEventListener('mousemove', checkMouseEvent, false);
        }, false);

        document.addEventListener('focus', function(e){
            if (e.target !== shouldNotFocus) return;
            if (!e.target.isContentEditable) return;
            document.body.appendChild(fixEl);
            fixEl.focus();
            fixEl.setSelectionRange(0,0);
            document.body.removeChild(fixEl);
        }, true);

    });
}
function getContentEditableRoot(el) {
    if (el.nodeType === 3) el = el.parentNode;
    if (!el.isContentEditable) return false;
    while (el) {
        var next = el.parentNode;
        if (next.isContentEditable) {
            el = next;
            continue
        }
        return el;
    }
}
于 2015-06-03T19:58:43.440 回答