当用户在 iframe 中按下按钮时,我试图动态插入表格。我使用的 insertHTML 方法没有锻炼。所以我使用了 pasteHTML 方法。内容现在被插入 iframe 的顶部。这是我写的代码......
代码.....
<html>
<head>
<script type="text/javascript">
var editorDoc;
function InitEditable ()
{
var editor = document.getElementById ("editor");
editorDoc = editor.contentWindow.document;
var editorBody = editorDoc.body;
if ('spellcheck' in editorBody)
{
editorBody.spellcheck = false;
}
if ('contentEditable' in editorBody)
{
editorBody.contentEditable = true;
}
else
{ // Firefox earlier than version 3
if ('designMode' in editorDoc)
{
// turn on designMode
editorDoc.designMode = "on";
}
}
}
function editorCommand(command)
{
editorDoc.execCommand (command, false, null);
}
function addTable()
{
editorDoc.focus();
var html = '<table border="1"><tr><td>1</td></tr></table>'
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount)
{
range = sel.getRangeAt(0);
range.deleteContents();
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ( (node = el.firstChild) )
{
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if (lastNode)
{
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}
</script>
</head>
<body onload="InitEditable ();">
<table bgcolor="red" border="1" width="65%" height="5%">
<tr><td width="5%"><img src="" onClick="editorCommand('bold')"></img></td>
<td> <img src="" onClick="addTable()"></img></td>
</tr></table>
<iframe id="editor" width="65%" height="70%">
</iframe>
<br/><br/>
<br/>
</body>
</html>