2016-03-04 81 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

希望它能帮助!