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

前端 未结 2 1819
梦如初夏
梦如初夏 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条回答
  • 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;
        }
    };
    
    0 讨论(0)
  • 2021-02-06 07:39

    I made a jsfiddle with a quick sample of how to look at the range of the selection and use the previousSibling property of the startContainer to find the button: jsfiddle

    Put the cursor in aaa and it will show the button is prev sibling. put it in ccc and bbb will show.

    So with this you could handle the keydown event of the div, check if key is backspace + previousSibling is your button, and remove it with jQuery.

    previousSibling is null if it is a textnode though, just FYI.

    0 讨论(0)
提交回复
热议问题