2012-08-13 65 views
0

我創建了一個非常簡單的rte,這裏是我的問題,我可以在iframe中獲取所選文本(designmode = true),但是我無法更改它。iframe change selection

HTML

<a onclick="change();">change</a> 
<iframe id="textEditor"></iframe> 

腳本文件

function $(Str1){return document.getElementById(Str1);} 
rte() 
{ 
    var texteditor=$('texteditor'); 
    textEditor.document.designMode="on"; 
    textEditor.document.body.contentEditable="True"; 
    textEditor.document.open(); 
    textEditor.document.close(); 
    textEditor.focus(); 

} 
function change() 
{ 
    var userSelection,range; 
    if (window.frames['textEditor'].getSelection) 
    { 
     userSelection=window.frames['textEditor'].getSelection(); 
    } 
    else if(document.frames['textEditor'].selection) 
    { 
     userSelection=document.frames['textEditor'].selection.createRange(); 
    } 
    if(userSelection.getRangeAt) 
    { 
     range=userSelection.getRangeAt(0); 
    } 
    else 
    { 
     range=document.frames['textEditor'].createRange(); 
     range.setStart(userSelection.anchorNode,userSelection.anchorOffset); 
     range.setEnd(userSelection.focusNode,userSelection.focusOffset); 
    } 
    range="<div style='color:#f00;'>" + range + "</div>"; 
} 
window.onload = rte(); 

回答

0

難道說的rte()函數引用 '文本編輯' 的第一線,而不是 '文本編輯'?

+0

你是對的,但是當我設置他們都相同的腳本給出了一個錯誤 – 2012-08-13 06:10:55

0

我找到了一種方法來解決它了,變函數應該是這樣的

function change() 
    if(document.selection) 
    { 
     sText=textEditor.document.selection.createRange(); 
     sText.execCommand("createlink","",""); 
     temp=sText.parentElement().innerHTML; 
     newNode=textEditor.document.createElement("h1"); 
     replacement=sText.parentElement().replaceNode(newNode); 
     newNode.innerHTML=temp; 
    } 
    else if(document.getSelection) 
    { 
     sText=textEditor.window.getSelection(); 
     myTag=textEditor.document.createElement("div"); 
     myTag.setAttribute("class","bold"); 
     sText.getRangeAt(0).surroundContents(myTag); 
    } 
}