如何删除具有 contentEditable 属性的 div 内的 HTML 元素?

发布于 2024-08-19 17:07:39 字数 212 浏览 4 评论 0原文

有这个html:

<div id="editable" contentEditable="true"  >
    <span contentEditable="false" >Text to delete</span>
</div>

需要用一个退格键删除跨度(以及里面的所有文本),这可能吗?

have this html:

<div id="editable" contentEditable="true"  >
    <span contentEditable="false" >Text to delete</span>
</div>

need that the span (and all text inside) is removed with a single backspace, is it possible?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

淑女气质 2024-08-26 17:07:39

事实证明这比我想象的要复杂。或者我让它变得比需要的更复杂。无论如何,这应该适用于所有大型浏览器:

function getLastTextNodeIn(node) {
    while (node) {
        if (node.nodeType == 3) {
            return node;
        } else {
            node = node.lastChild;
        }
    }
}

function isRangeAfterNode(range, node) {
    var nodeRange, lastTextNode;
    if (range.compareBoundaryPoints) {
        nodeRange = document.createRange();
        lastTextNode = getLastTextNodeIn(node);
        nodeRange.selectNodeContents(lastTextNode);
        nodeRange.collapse(false);
        return range.compareBoundaryPoints(range.START_TO_END, nodeRange) > -1;
    } else if (range.compareEndPoints) {
        if (node.nodeType == 1) {
            nodeRange = document.body.createTextRange();
            nodeRange.moveToElementText(node);
            nodeRange.collapse(false);
            return range.compareEndPoints("StartToEnd", nodeRange) > -1;
        } else {
            return false;
        }
    }
}

document.getElementById("editable").onkeydown = function(evt) {
    var sel, range, node, nodeToDelete, nextNode, nodeRange;
    evt = evt || window.event;
    if (evt.keyCode == 8) {
        // Get the DOM node containing the start of the selection
        if (window.getSelection && window.getSelection().getRangeAt) {
            range = window.getSelection().getRangeAt(0);
        } else if (document.selection && document.selection.createRange) {
            range = document.selection.createRange();
        }

        if (range) {
            node = this.lastChild;
            while (node) {
                if ( isRangeAfterNode(range, node) ) {
                    nodeToDelete = node;
                    break;
                } else {
                    node = node.previousSibling;
                }
            }

            if (nodeToDelete) {
                this.removeChild(nodeToDelete);
            }
        }
        return false;
    }
};

This turned out to be more complicated than I thought. Or I've made it more complicated than it needs to be. Anyway, this should work in all the big browsers:

function getLastTextNodeIn(node) {
    while (node) {
        if (node.nodeType == 3) {
            return node;
        } else {
            node = node.lastChild;
        }
    }
}

function isRangeAfterNode(range, node) {
    var nodeRange, lastTextNode;
    if (range.compareBoundaryPoints) {
        nodeRange = document.createRange();
        lastTextNode = getLastTextNodeIn(node);
        nodeRange.selectNodeContents(lastTextNode);
        nodeRange.collapse(false);
        return range.compareBoundaryPoints(range.START_TO_END, nodeRange) > -1;
    } else if (range.compareEndPoints) {
        if (node.nodeType == 1) {
            nodeRange = document.body.createTextRange();
            nodeRange.moveToElementText(node);
            nodeRange.collapse(false);
            return range.compareEndPoints("StartToEnd", nodeRange) > -1;
        } else {
            return false;
        }
    }
}

document.getElementById("editable").onkeydown = function(evt) {
    var sel, range, node, nodeToDelete, nextNode, nodeRange;
    evt = evt || window.event;
    if (evt.keyCode == 8) {
        // Get the DOM node containing the start of the selection
        if (window.getSelection && window.getSelection().getRangeAt) {
            range = window.getSelection().getRangeAt(0);
        } else if (document.selection && document.selection.createRange) {
            range = document.selection.createRange();
        }

        if (range) {
            node = this.lastChild;
            while (node) {
                if ( isRangeAfterNode(range, node) ) {
                    nodeToDelete = node;
                    break;
                } else {
                    node = node.previousSibling;
                }
            }

            if (nodeToDelete) {
                this.removeChild(nodeToDelete);
            }
        }
        return false;
    }
};
深空失忆 2024-08-26 17:07:39

因为您想要删除整个元素,所以最好将其设置为 contenteditable="false",这样浏览器就不会删除元素的内容。

然后您可以使用此属性在事件处理程序中进行测试,如下所示:

$('#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();
        }
    }
});

jsfiddle 上的演示

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文