contenteditable div: IE8 not happy with backspace remove of HTML element

前端 未结 2 1821
梦如初夏
梦如初夏 2021-02-06 06:59

I am making use of a contenteditable div in combination with the rangy Javascript library to insert HTML at the cursor position.

End of the day the contents of the div c

2条回答
  •  梦毁少年i
    2021-02-06 07:29

    My suggestion would be to first check the caret is positioned after the non-editable node, and if so, create a range that starts immediately after the non-editable element and ends at the caret position. Check whether the text in this range is empty. If it is, that means the caret is placed directly after the non-editable element, so in that case remove the element. Finally, place the caret where the non-editable had been.

    Live demo: http://jsfiddle.net/timdown/vu3ub/

    Code:

    document.onkeypress = function(e) {
        e = e || window.event;
        var keyCode = e.which || e.keyCode;
        if (keyCode !== 8) {
            return;
        }
    
        var sel = rangy.getSelection();
        if (sel.rangeCount === 0) {
            return;
        }
    
        var selRange = sel.getRangeAt(0);
        if (!selRange.collapsed) {
            return;
        }
    
        var nonEditable = document.getElementById("nonEditable");
        if (!nonEditable) {
            return;
        }
    
        // Check the caret is located after the non-editable element
        var range = rangy.createRange();
        range.collapseAfter(nonEditable);
    
        if (selRange.compareBoundaryPoints(range.START_TO_END, range) == -1) {
            return;
        }
    
        // Check whether there is any text between the caret and the
        // non-editable element. If not, delete the element and move
        // the caret to where it had been
        range.setEnd(selRange.startContainer, selRange.startOffset);
        if (range.toString() === "") {
            selRange.collapseBefore(nonEditable);
            nonEditable.parentNode.removeChild(nonEditable);
            sel.setSingleRange(selRange);
    
            // Prevent the default browser behaviour
            return false;
        }
    };
    

提交回复
热议问题