在iframe中的光标位置插入html内容

时间:2013-03-10 13:33:41

标签: html iframe

当用户将按钮按入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>

0 个答案:

没有答案