【问题标题】:Identify whether the selected text in a web page is bold nor not识别网页中所选文本是否为粗体
【发布时间】:2010-08-04 19:34:23
【问题描述】:

我正在尝试确定所选文本(在 Firefox 中)是否为粗体?例如:

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

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

用户可以选择部分粗体文本,也可以选择完整的粗体文本。这是我想要做的:

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

你能帮帮我吗?

谢谢
斯里坎特

【问题讨论】:

  • 这是在可编辑元素(或文档)中吗?

标签: javascript format range selection bold


【解决方案1】:

如果选择在可编辑元素或文档中,这很简单:

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

否则,这有点棘手:在非 IE 浏览器中,您必须暂时使文档可编辑:

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;
}

【讨论】:

  • 非常感谢。我现在将解决此解决方法。
  • 此功能 (queryCommandState ) 现已弃用...:/
  • @CyrilN。如果有一个处理范围的替代 API(这是你从选择中得到的),我不知道。我对从 Web 平台中删除 API 而不进行替换感到不高兴。在这种情况下,您可以手动遍历选择或部分选择的元素(here's a starting point,尽管您需要过滤掉非元素节点)并使用getComputedStyle() 来检查每个。
  • @TimDown 是的,我尝试这样做,最后回到使用 queryCommandState 并假设在某个时候,一个很棒的开发人员会构建一个兼容的 API :D
猜你喜欢
  • 2019-09-25
  • 2016-08-31
  • 2012-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-01
相关资源
最近更新 更多