Учитывать ли контент только при нажатии элемента?

Кажется, что контент доступен только вам, когда вы нажимаете на страницу.

Как я могу сделать фокус только тогда, когда элемент, который он сам нажал, но не вне элемента?

См. демонстрацию: http://jsbin.com/iTEkUKa/1/edit

Попробуйте щелкнуть за пределами любого из полей, это все еще приводит к фокусу, вот и проблема.

Ответ 1

Используйте этот script:

Это легко объясняется так:

При щелчке за пределами contenteditable-element получите элемент contenteditable, который будет сфокусирован.
Если в следующем фокусном событии этот элемент получает фокус, удалите его.

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;
    }
}