具有 DOM 范围和内容可编辑的构建编辑器
Building editor with DOM Range and content editable
我正在尝试使用 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,但我希望它有所帮助。这应该适用于简单情况。我不知道它会如何应对更复杂的案件。使用富文本编辑,事情可能会变得非常丑陋。
随时通知我:)
相关文章:
- CKEditor Widget-阻止编辑可编辑元素本身
- 如何在angularJS中编辑时,如果DB中的值为true,则设置复选框,如果值为false,则取消选中复选框
- 我应该如何从xml文件构建一个javascript页面
- 高亮显示时编辑文本大小和颜色
- 剑道UI内联编辑:如何在点击其他按钮时隐藏按钮
- 如何在DOM元素上按类型构建此函数
- 将事件聚焦/模糊在可编辑内容的元素上
- Sencha Touch构建-排除文件
- RubyonRails——构建交互式接口应该朝哪个方向发展
- 如何使用HTML5和Raphael JS构建图像编辑器
- 具有 DOM 范围和内容可编辑的构建编辑器
- 如何构建一个轻量级的在线文本编辑器
- Dart编辑器:Pub构建会产生不正常的文件
- d3是构建自由格式图表编辑器的好选择吗?
- 构建一个简单的所见即所得编辑器
- 富文本编辑器是如何工作的,如何构建一个基本的文本编辑器
- 用HTML 5和Canvas构建图像编辑器
- 是否需要在编辑javascript文件后进行构建
- 使用Flux构建一个编辑表单,它实际向服务器发送数据:动作、存储、视图
- 我'我试图通过使用codemmirror编辑器构建D3.js,但我在那里输入的任何东西都不能被D3.js正确地可