确定网页中选定的文本是否为粗体

编程入门 行业动态 更新时间:2024-10-11 15:19:19
本文介绍了确定网页中选定的文本是否为粗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我试图确定一个选定的文本(在Firefox中)是否大胆?例如:

< p>某些< b>文字已输入< / b>这里< / p为H. < p>有些< span style =font-weight:bold>输入了更多文字< / span>这里< / p为H.

用户既可以选择粗体文本的一部分,也可以选择全粗体文本。这是我想要做的: pre $函数isSelectedBold(){ var r = window.getSelection() .getRangeAt(0); //然后呢? $ / code $ / pre 您能帮我吗?

谢谢 Srikanth

解决方案

如果所选内容位于可编辑元素或文档中,这很简单: pre $ function selectionIsBold(){ var isBold = false; if(document.queryCommandState){ isBold = document.queryCommandState(bold); } return isBold; $ b

否则,这有点麻烦:在非IE浏览器中,必须暂时使文档可编辑: pre $ 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; }

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

解决方案

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

更多推荐

确定网页中选定的文本是否为粗体

本文发布于:2023-11-10 14:33:06,感谢您对本站的认可!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:粗体   文本   网页

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!