我正在尝试使用 DOM Range 构建文本编辑器。假设我正在尝试将所选文本加粗。我使用以下代码执行此操作。但是,如果粗体已经加粗,我不知道如何删除粗体。我正在尝试在不使用 execCommand 函数的情况下完成此操作。
this.selection = window.getSelection();
this.range = this.selection.getRangeAt(0);
let textNode = document.createTextNode(this.range.toString());
let replaceElm = document.createElement('strong');
replaceElm.appendChild(textNode);
this.range.deleteContents();
this.range.insertNode(replaceElm);
this.selection.removeAllRanges();
基本上,如果选择范围包含在<strong>
标签中,我想删除它。
好的,
所以我起草了这段代码。它基本上抓取当前选定的节点,获取文本内容并删除样式标签。
// Grab the currenlty selected node
// e.g. selectedNode will equal '<strong>My bolded text</strong>'
const selectedNode = getSelectedNode();
// "Clean" the selected node. By clean I mean extracting the text
// selectedNode.textContent will return "My bolded text"
/// cleandNode will be a newly created text type node [MDN link for text nodes][1]
const cleanedNode = document.createTextNode(selectedNode.textContent);
// Remove the strong tag
// Ok so now we have the node prepared.
// We simply replace the existing strong styled node with the "clean" one.
// a.k.a undoing the strong style.
selectedNode.parentNode.replaceChild(cleanedNode, selectedNode);
// This function simply gets the current selected node.
// If you were to select 'My bolded text' it will return
// the node '<strong> My bolded text</strong>'
function getSelectedNode() {
var node,selection;
if (window.getSelection) {
selection = getSelection();
node = selection.anchorNode;
}
if (!node && document.selection) {
selection = document.selection
var range = selection.getRangeAt ? selection.getRangeAt(0) : selection.createRange();
node = range.commonAncestorContainer ? range.commonAncestorContainer :
range.parentElement ? range.parentElement() : range.item(0);
}
if (node) {
return (node.nodeName == "#text" ? node.parentNode : node);
}
};
我不知道这是否是一个"生产"就绪的soutes,但我希望它有所帮助。这应该适用于简单情况。我不知道它会如何应对更复杂的案件。使用富文本编辑,事情可能会变得非常丑陋。
随时通知我:)