Identify whether the selected text in a web page is bold nor not(识别网页中所选文本是否为粗体)
问题描述
我正在尝试确定所选文本(在 Firefox 中)是否为粗体?例如:
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?
}
你能帮帮我吗?
谢谢
斯里坎特
推荐答案
如果选择在可编辑元素或文档中,这很简单:
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;
}
否则,这有点棘手:在非 IE 浏览器中,您必须暂时使文档可
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;
}
这篇关于识别网页中所选文本是否为粗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:识别网页中所选文本是否为粗体


基础教程推荐
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01