How to delete an HTML element inside a div with attribute contentEditable?

前端 未结 3 756
旧时难觅i
旧时难觅i 2020-12-02 18:13

have this html:

Text to delete
3条回答
  •  情话喂你
    2020-12-02 18:27

    Because you want to delete the whole element, it's better to make it contenteditable="false" so that browser won't let the contents of an element to be deleted.

    Then you can use this attribute for tests in event handler as follows:

    $('#editable').on('keydown', function (event) {
        if (window.getSelection && event.which == 8) { // backspace
            // fix backspace bug in FF
            // https://bugzilla.mozilla.org/show_bug.cgi?id=685445
            var selection = window.getSelection();
            if (!selection.isCollapsed || !selection.rangeCount) {
                return;
            }
    
            var curRange = selection.getRangeAt(selection.rangeCount - 1);
            if (curRange.commonAncestorContainer.nodeType == 3 && curRange.startOffset > 0) {
                // we are in child selection. The characters of the text node is being deleted
                return;
            }
    
            var range = document.createRange();
            if (selection.anchorNode != this) {
                // selection is in character mode. expand it to the whole editable field
                range.selectNodeContents(this);
                range.setEndBefore(selection.anchorNode);
            } else if (selection.anchorOffset > 0) {
                range.setEnd(this, selection.anchorOffset);
            } else {
                // reached the beginning of editable field
                return;
            }
            range.setStart(this, range.endOffset - 1);
    
    
            var previousNode = range.cloneContents().lastChild;
            if (previousNode && previousNode.contentEditable == 'false') {
                // this is some rich content, e.g. smile. We should help the user to delete it
                range.deleteContents();
                event.preventDefault();
            }
        }
    });
    

    demo on jsfiddle

提交回复
热议问题