当您单击按钮时,我会将选定的文本包装在span标签中。如果我随后选择另一段文本并单击按钮,则该文本也将包裹在标签中。但是,当我选择已经用span标记包裹的一段文本时,我想删除这些标记以不显示文本,而不是将这些标记包裹在更多标记中。

HTML

<div contenteditable="true" class="textEditor">Some random text.</div>

<a href="#" class="embolden">Bold</a>

JS
$('.embolden').click(function(){
    var highlight = window.getSelection();
    var span = '<span class="bold">' + highlight + '</span>';
    var text = $('.textEditor').html();
    $('.textEditor').html(text.replace(highlight, span));
});

JSFiddle Demo

我可能对此要求很满意,但我只选择了已经用span标记包裹的一段文本,但不是全部,我想在选择开始时关闭原始标记,打开一个之后立即添加新标签,然后在选择的结尾处关闭新标签,然后再打开一个新标签。

最佳答案

当您可以使用内置功能时,为什么要尝试用粗体显示文本。现代浏览器实现了execCommand函数,该函数允许在文本上加粗,加下划线等。您可以只写:

$('.embolden').click(function(){
    document.execCommand('bold');
});

并将选定的文本设置为粗体,如果已经将其设置为粗体,则将删除文本样式。

可以在here中找到命令列表和一些文档。 (有关浏览器支持的更多信息here)。

$(document).ready(function() {
  $('#jBold').click(function() {
    document.execCommand('bold');
  });
});
#fake_textarea {
  width: 100%;
  height: 200px;
  border: 1px solid red;
}

button {
  font-weigth: bold;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="jBold"><b>B</b></button>
<div id='fake_textarea' contenteditable>
  Select some text and click the button to make it bold...
  <br>Or write your own text
</div>

关于javascript - 将所选文字设为粗体/非粗体,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20880271/

10-15 16:20