son*_*lis 16 javascript contenteditable execcommand
上下文是Chrome 37.0.2062.120 m.
我正在使用execCommand将html插入到可编辑的div中.我的execCommand调用如下所示:
function insertHTML(){
document.execCommand('insertHTML', false, '<span id="myId">hi</span>');
}
Run Code Online (Sandbox Code Playgroud)
当可编辑的div看起来像这样:
<div contenteditable="true">
some [insertion point] content
</div>
Run Code Online (Sandbox Code Playgroud)
我使用execCommand将html插入一个contenteditable div,HTML的所有属性都按预期插入,我最终得到这个:
<div contenteditable="true">
some <span id="myId">hi</span> content
</div>
Run Code Online (Sandbox Code Playgroud)
但是,当我在此结构中插入完全相同的html时:
<div contenteditable="true">
some content
<div>more [insertion point] content</div>
</div>
Run Code Online (Sandbox Code Playgroud)
从插入的跨度中删除属性,它最终看起来像这样:
<div contenteditable="true">
some content
<div>more <span style="font-size: 10pt;">hi</span> content</div>
</div>
Run Code Online (Sandbox Code Playgroud)
有没有办法防止这种情况发生?
Tim*_*own 24
在这个特殊情况下,我建议使用Range.insertNode,这将使您完全控制插入的内容:
function insertHTML() {
var sel, range;
if (window.getSelection && (sel = window.getSelection()).rangeCount) {
range = sel.getRangeAt(0);
range.collapse(true);
var span = document.createElement("span");
span.id = "myId";
span.appendChild( document.createTextNode("hi") );
range.insertNode(span);
// Move the caret immediately after the inserted span
range.setStartAfter(span);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
Run Code Online (Sandbox Code Playgroud)
function isOrIsAncestorOf(ancestor, descendant) {
var n = descendant;
while (n) {
if (n === ancestor) {
return true;
} else {
n = n.parentNode;
}
}
return false;
}
function nodeContainsSelection(node) {
var sel, range;
if (window.getSelection && (sel = window.getSelection()).rangeCount) {
range = sel.getRangeAt(0);
return isOrIsAncestorOf(node, range.commonAncestorContainer);
}
return false;
}
function insertHTML() {
var sel, range;
if (window.getSelection && (sel = window.getSelection()).rangeCount) {
range = sel.getRangeAt(0);
range.collapse(true);
var span = document.createElement("span");
span.id = "myId";
span.appendChild( document.createTextNode("hi") );
range.insertNode(span);
// Move the caret immediately after the inserted span
range.setStartAfter(span);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
window.onload = function() {
document.getElementById("inserter").onmousedown = function() {
var editor = document.getElementById("editor");
if (nodeContainsSelection(editor)) {
insertHTML();
return false;
}
};
};Run Code Online (Sandbox Code Playgroud)
span {
font-weight: bold;
color: green;
}Run Code Online (Sandbox Code Playgroud)
<input type="button" id="inserter" value="Insert span">
<div contenteditable="true" id="editor">
some content
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14558 次 |
| 最近记录: |