选择内容时,Javascript用div包装它

时间:2016-03-04 18:53:28

标签: javascript jquery textarea

让我们说我有一个textarea和粗体按钮:

<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
  3. jsfiddle:https://jsfiddle.net/5feLm4jn/3/

2 个答案:

答案 0 :(得分:0)

截至今天,无法在<textarea>内启用富文本格式。您必须使用<div>属性contenteditable。例如:

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

已经提供了完整可行的解释(以及JSFiddle示例):Make selected text bold/unbold

希望它有所帮助!

答案 1 :(得分:0)

使用content editable div,您可以直接使用文档中的document.execCommandbold selected 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>