最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Identify whether the selected text in a web page is bold nor not - Stack Overflow

programmeradmin3浏览0评论

I am trying to identify whether a selected text (in Firefox) is bold or not? For e.g.:

<p>Some <b>text is typed</b> here</p>

<p>Some <span style="font-weight: bold">more text is typed</span> here</p>

The user can either select a part of bold text, or the full bold text. Here is what I am trying to do:

function isSelectedBold(){
    var r = window.getSelection().getRangeAt(0);
    // then what?
}

Could you please help me?

Thanks
Srikanth

I am trying to identify whether a selected text (in Firefox) is bold or not? For e.g.:

<p>Some <b>text is typed</b> here</p>

<p>Some <span style="font-weight: bold">more text is typed</span> here</p>

The user can either select a part of bold text, or the full bold text. Here is what I am trying to do:

function isSelectedBold(){
    var r = window.getSelection().getRangeAt(0);
    // then what?
}

Could you please help me?

Thanks
Srikanth

Share Improve this question asked Aug 4, 2010 at 10:30 Srikanth VittalSrikanth Vittal 4867 silver badges22 bronze badges 1
  • Is this in an editable element (or document)? – Tim Down Commented Aug 4, 2010 at 11:19
Add a ment  | 

1 Answer 1

Reset to default 16

If the selection is within an editable element or document, this is simple:

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

Otherwise, it's a little trickier: in non-IE browsers, you'll have to temporarily make the document editable:

function selectionIsBold() {
    var range, isBold = false;
    if (window.getSelection) {
        var sel = window.getSelection();
        if (sel && sel.getRangeAt && sel.rangeCount) {
            range = sel.getRangeAt(0);
            document.designMode = "on";
            sel.removeAllRanges();
            sel.addRange(range);
        }
    }
    if (document.queryCommandState) {
        isBold = document.queryCommandState("bold");
    }
    if (document.designMode == "on") {
        document.designMode = "off";
    }
    return isBold;
}
发布评论

评论列表(0)

  1. 暂无评论