将所选文本设为粗体/非粗体 [英] Make selected text bold/unbold

查看:148
本文介绍了将所选文本设为粗体/非粗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您单击按钮时,我将所选文本包装在span标签中。如果我然后选择不同的文本并单击按钮,该文本也会包含在标签中。但是,当我选择一段已经包含在span标签中的文本时,我想删除这些标签以取消插入文本,而不是将这些标签包装在更多标签中。

I'm wrapping the selected text in span tags, when you click a button. If I then select a different piece of text and click the button, that text also gets wrapped in tags. However, when I select a piece of text that's already wrapped in span tags, I'd like to remove those tags to unembolden the text, instead of wrapping those tags in more tags.

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演示

我可能对此请求感到贪婪,但我选择的部分文本已经包含在span标签中,但不是所有这一切,我想在选择开始时关闭原始标签,然后打开一个新标签,然后在选择结束时关闭新标签并在此之后打开一个新标签。

I'm probably getting greedy with this request but I select just part of a piece of text that's already wrapped in span tags, but not all of it, I'd like to close the original tag at the start of the selection, open a new tag right after that, then close the new tag at the end of the selection and open a new tag after that.

推荐答案

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

Why you are trying to bold text doing it by hand when you can use built in feature. Modern browsers implements execCommand function that allows to bold, underline etc. on text. You can write just:

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

并且所选文本将变为粗体,如果它已经是粗体,则将删除文本样式。

and selected text will be made bold and if it's already bold, the text styling will be removed.

可以找到一个命令列表和一个小文档这里。 (有关浏览器支持的更多信息,请此处)。

A list of commands and a little doc can be found here. (More about browser support 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>

这篇关于将所选文本设为粗体/非粗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆