2011-05-15 158 views
2

我正在嘗試編寫一個腳本,用於在Chrome中的iframe中拖放圖像。在Chrome中拖放圖像

<html> 
<head> 
    <script language="JavaScript"> 

     function InsertImage(ev) 
     { 
      alert("drag function called"); 
      var _image = document.createElement("image"); 
      var _sel = _win.getSelection(); 
      if(!_sel.isCollapsed) 
      { 
       _sel.deleteFromDocument(); 
      } 
      try{ 
       var _range = _sel.getRangeAt(0); 
      } 
      catch(e) 
      { 
       _range = _doc.createRange(); 
       alert("000000:::: "+e); 
       alert("_range is ::"+_range); 
      } 
      if(!_range) 
      { 
       _range = _doc.createRange(); 
      } 
      alert("range is ::::"+_range); 
      try 
      { 
       _range.insertNode(_image); 
      } 
      catch(e) 
      { 
       alert("1111:: "+e); 
      } 
      _range.insertNode(_image); 


     } 

     function init() 
     { 
      _iframe = document.createElement("iframe"); 
      _iframe.id = "view"; 
      _iframe.style.height = "250px"; 
      _iframe.style.width = "600px"; 
      _iframe.style.top = "20px"; 
      _iframe.style.left = "200px"; 
      _iframe.style.position = "absolute"; 
      _iframe.style.border = "2px solid lightBlue"; 
      document.body.appendChild(_iframe); 
       _iframe.contentDocument.designMode="on";//No I18N 
       _win = _iframe.contentWindow; 
       _win.focus(); 
       _doc = _win.document; //making it global variable 

       _doc.body.innerHTML = "<p>aaaa bbbb cccc dddd eeee ffff gggg hhhh iiii jjjj kkkk llll mmmm nnnn oooo pppp qqqq rrrr ssss tttt uuuu vvvv wwww xxxx yyyy zzzz</p>"; 
       _doc.addEventListener("dragover",InsertImage,false); 

     } 

    </script> 
</head> 
<body onLoad="init()"> 
    <div style="position:absolute;top:300px;left:100px "> 
     <p> this si a testing doc.here, we test the things</p> 
    </div> 
</body> 

是不工作.. 在Chrome控制檯,我得到這個錯誤信息:

Uncaught Error: WRONG_DOCUMENT_ERR: DOM Exception 4

蹊蹺的選擇和範圍,我猜。

回答

1

DOMException.WRONG_DOCUMENT_ERR甲拋出異常每當身後DOM操作方法與那些的兩個不同DOMDocuments一部分的節點工作。您必須使用DOMDocument.importNode方法,以便從一個文檔到另一個文檔的導入 DOMNode。

我想你必須將圖像節點導入到iFrame的文檔

像(未經測試):

var nodeToImport = _doc.importNode(_image, true); 
//nodeToImport can now be added to the second document 
_doc.appendChild(nodeToImport); 

more here

+0

感謝卡斯帕,它現在的工作,唯一的事情是我必須使用「** _ doc.appendChild(nodeToImport); **」在相關的地方.. – Mickey 2011-05-16 16:03:55