仅在单击元素时才关注可编辑内容? [英] Only focus on contenteditable when the element is clicked?

查看:108
本文介绍了仅在单击元素时才关注可编辑内容?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎contenteditable可以使您在页面上单击的任何地方都获得焦点。

It seems with contenteditable you get the focus wherever you click on the page.

仅当单击自身元素时,如何才能获得焦点?

How can I make the focus only when the element it self is clicked, but not outside the element?

请参阅演示:
http://jsbin.com/iTEkUKa/1/edit

尝试在任何框外单击,仍然会引起焦点,那就是问题。

Try to click outside any of the boxes, it still results in focus, thats the problem.

推荐答案

使用以下脚本:

工作原理很容易解释像这样:

It works easily explained like that:

在contenteditable-element外部单击时,将获得将要聚焦的contenteditable-element。

如果在以下焦点事件中,

On click outside a contenteditable-element get the contenteditable-element that will be focused.
If, on the following focus event, this element gets the focus, remove it.

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

这篇关于仅在单击元素时才关注可编辑内容?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆