在CONTENTEDITABLE DIV设置插入符的位置(Set caret position in

2019-07-18 06:31发布

介绍

当编辑CONTENTEDITABLE DOM对象的内容,不同的浏览器有不同的行为。 例如,火狐18.0创建一个新段落( <p>或换行符<br/>在一些情况下,同时铬24创建一个<div>

为了解决这个问题,我在听DOMNodeInserted事件,并与p标签更换新插入的节点。


问题

问题是放置插入符到位。 我在SO对此同一主题,但没有提供答案很成功 ,至少在Chrome 24中读吨的职位


的jsfiddle

obj.addEventListener("DOMNodeInserted", onNodeInsert, false);

function onNodeInsert(e) {
    var range    = document.createRange(),
        sel      = window.getSelection(),
        newNode  = e.target,
        tagName  = newNode.tagName.toLowerCase(),
        lnbrNode = document.createElement('br'),
        pNode    = document.createElement('p');

    if (tagName === 'div' && newNode.getAttribute("id") === null) {
        // First we remove the event listener so that it doesn't get triggered again
        this.removeEventListener('DOMNodeInserted', onNodeInsert, false);

        // Creates a p node and removes the div
        newNode.parentNode.replaceChild(pNode, newNode);
        pNode.appendChild(lnbrNode);

        // Places the caret where it belongs
        range.setStart(pNode, 0);
        sel.removeAllRanges();
        sel.addRange(range);    

        //We can restore the event listener now
        this.addEventListener("DOMNodeInserted", onNodeInsert, false);
    }
}

Answer 1:

对于那些像我这样谁可能会遇到同样的问题,这是我的脏修复...


相关代码

的jsfiddle

obj.addEventListener("DOMNodeInserted", onNodeInsert, false);

function onNodeInsert(e) {
    var range    = document.createRange(),
        sel      = window.getSelection(),
        newNode  = e.target,
        tagName  = newNode.tagName.toLowerCase(),
        lnbrNode = document.createElement('br'),
        pNode    = document.createElement('p');

    if (tagName === 'div' && newNode.getAttribute("id") === null) {
        // First we remove the event listener so that it doesn't get triggered again
        this.removeEventListener('DOMNodeInserted', onNodeInsert, false);

        // Creates a p node and removes the div
        newNode.parentNode.replaceChild(pNode, newNode);
        pNode.appendChild(lnbrNode);

        // Places the caret where it belongs
        var placeCursor = function () {
            range.setStart(pNode, 0);
            sel.removeAllRanges();
            sel.addRange(range);    
        }

        //placeCursor(); // DOES NOT WORK (cursor disappears)
        setTimeout(placeCursor,1); // WORKS

        //We can restore the event listener now
        this.addEventListener("DOMNodeInserted", onNodeInsert, false);
    }
}


文章来源: Set caret position in contenteditable div