2014-06-16 65 views
1

我想向粗體添加(參見插圖)。如果我這樣做:JavaScript將粗體文本添加到框架

 p:function{ 
     sel = this.getSelection().getRangeAt(0); 
     var caretPosition = sel.endOffset; 
     var existingText = this.iframe[0].contentWindow.document.body.innerText; 

     var before = existingText.substring(0, caretPosition); 
     var after = existingText.substring(caretPosition); 

     this.iframe[0].contentWindow.document.body.innerHTML= before 
     +'**<b>**(see illustration)**</b>** ' + after; 
     }, 

然後我寫的所有文本(請參閱插圖變成粗體)。

enter image description here enter image description here

+1

['的execCommand()'] (https://developer.mozilla.org/en-US/docs/Web/API/document.execCommand )可能有幫助? – Teemu

回答

3

如果你想創建一個可編輯iframe使用粗體,斜體或其他命令,你可以使用底層瀏覽器的命令,你可以通過execCommand方法火。

你可以看到有資源,以獲取更多信息:
https://developer.mozilla.org/en-US/docs/Web/API/document.execCommand
https://developer.mozilla.org/en/docs/Rich-Text_Editing_in_Mozilla

這些方法是由所有現代瀏覽器都支持。

+0

謝謝,我發現了一種使用execCommand的方法,但只有當用戶選擇文本時。我想要一種預先插入粗體值的方法 – alex1111

+0

@ alex1111是否要在'iframe'中添加一些粗體文本? –

+0

@ABFORCE yessss – alex1111

1

我提供了一個簡單的例子,告訴您如何execCommand工作

<iframe id = "my-editable"> 
    <html> 
     <body contenteditable = "true"> 
     </body> 
    </html> 
</iframe> 

JavaScript代碼:

var iframe = document.getElementById('my-editable'); 
var iframeDoc = iframe.contentWindow.document; 

// type and select some text into iframe 
// For making selected text to be bold, just execute the following command 
iframeDoc.execCommand('bold'); 

UPDATE

var body = iframeDoc.body; 
body.innerHTML = body.innerHTML + '<b>' + 'your bold text' + '</b>' + 'your boldless text' 
+0

謝謝,但我不想讓選定的文本變成粗體,我想插入一個大膽的文本+粗體文本+粗體文本:) – alex1111

+0

@ alex1111這很容易,稍後我會看到我的編輯 –

+0

我試過這個,但有一個問題:當我添加更多的文字到粗體文本的末尾時,這個添加的文本也是粗體,我不想要那個.. – alex1111