我正在尝试确定所选文本(在 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?
}
你能帮帮我吗?
谢谢
斯里坎特
最佳答案
如果选择在可编辑元素或文档中,这很简单:
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;
}
关于javascript - 识别网页中选中的文本是否为粗体,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3404618/