如何检查所选文字是否为粗体(可编辑) [英] How to check, the selected text is bold or not (contenteditable)

查看:107
本文介绍了如何检查所选文字是否为粗体(可编辑)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用html内置的contenteditable功能实现自定义文本编辑器.我需要知道用户何时在文本编辑器上选择了文本是否为粗体.

I'm implementing a custom text editor using html inbuilt contenteditable feature. I need to know when user selected a text on the text editor whether it's bold or not.

这是我现在拥有的:

HTML

<button onclick="boldit()">B</button>
<div id="editor" contenteditable="true" class="email-body">
    This is an <strong>editable</strong> paragraph.
</div>

JavaScript

Javascript

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

推荐答案

jQuery(function($) {
    $('.embolden').click(function(){
        if(selectionIsBold()){
          alert('bold');
        }
        else {
          alert('not bold');
        }
    });
});

function selectionIsBold() {
    var isBold = false;
    if (document.queryCommandState) {
        isBold = document.queryCommandState("bold");
    }
    return isBold;
}

.bold {
    font-weight: bold;
}

<div contenteditable="true" class="textEditor">Some <span class="bold">random </span>text.</div>
<a href="#" class="embolden">Is Bold Text</a>
<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"
  integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
  crossorigin="anonymous"></script>

突出显示文本,然后单击链接.

Highlight the text and click on the link.

这篇关于如何检查所选文字是否为粗体(可编辑)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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