2016-03-04 37 views
1

包裹它比方說,我有這樣的一個textarea和大膽的按鈕:的Javascript選擇內容時,用DIV

<div class="main"> 
    <textarea cols="60" rows="12"> 
    Lorem ipsum dolor sit amet... 
    </textarea> 
</div> 

<br> 
<button onclick="bold()">Bold</button> 

當我選擇(高亮顯示),用鼠標的內容,點擊大膽的按鈕,我希望它來包裝帶吊牌的選擇,例如:

<b>content</b> 

這就是我有這麼遠,但:

bold = function() {  
    var selection = window.getSelection().getRangeAt(0); 
    var selectedText = selection.extractContents(); 
    var span = document.createElement("b");  
    span.appendChild(selectedText); 
    selection.insertNode(span); 
} 
  1. 我怎樣才能使它與textrea工作太
  2. 我怎樣才能使它爲主要的div只工作

的jsfiddle:https://jsfiddle.net/5feLm4jn/3/

回答

0

使用content editablediv,你可以直接使用document.execCommandboldselected text在文檔中。


段:

function bold() { 
 
    document.execCommand('bold'); 
 
} 
 

 
function getSelectedText() { 
 
    var html2 = "", 
 
    html_changed = ""; 
 
    if (window.getSelection) { 
 
    html2 = window.getSelection().toString(); 
 
    } else if (document.selection && document.selection.type != "Control") { 
 
    html2 = document.selection.createRange().text; 
 
    } 
 
    html_changed = "<div>" + html2 + "</div>"; 
 
    var temp = document.getElementById("div"); 
 
    var temp_text = ""; 
 
    temp_text = temp.innerHTML; 
 
    var str = temp_text; 
 
    str = str.replace(html2, html_changed); 
 
    temp.innerHTML = temp_text; 
 
}
<div class="main" contenteditable id="div"> 
 
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptas, asperiores quidem ab neque molestias voluptatum amet possimus dolore rem enim error, eaque pariatur adipisci praesentium consequuntur! Rerum maxime eveniet ipsam est voluptas, facere 
 
    sequi cupiditate dolor exercitationem aspernatur distinctio in animi beatae earum! Ducimus provident ipsa vero in natus unde consequuntur ut, sapiente, reiciendis cumque illum exercitationem inventore asperiores enim architecto! Eveniet unde ipsa laudantium 
 
    facilis placeat obcaecati quam magnam quibusdam. 
 
</div> 
 

 
<br> 
 
<button id="bold" onclick="getSelectedText()">Bold</button>

+0

它的工作,謝謝! – user4571629

+0

我該如何做到這一點與自定義的?如果我想用內容包裝它,我正在嘗試使用formatBlock,但它不會僅僅爲我的選擇做 – user4571629

+0

@ user4571629:請檢查我更新的代碼段 – stark

0

截至今天,有沒有辦法在<textarea>中啓用富文本格式。您必須使用具有contenteditable屬性的<div>。例如:

<div id="foo" contenteditable> ... </div> 

完整可行的解釋(用的jsfiddle例如,沿着)已提供不已:Make selected text bold/unbold

希望它能幫助!