document.queryCommandState("superscript"); //always return false
document.queryCommandState("bold"); // works fine
如何检测可编辑元素中的上标或下标?
document.queryCommandState("superscript"); //always return false
document.queryCommandState("bold"); // works fine
<sub />
/<sup />
元素的样式有关。在@tim-down的示例中,使用的是默认样式。我更新了fiddle(http://jsfiddle.net/alarie/vzxh3818/)以使用某些样式,然后queryCommandState
将返回false
。(在这种情况下,实际上是vertical-align: baseline;
属性破坏了它)<sub>
/<sup>
而不是 CSS vertical-align,而 strikethrough 和 underline 没有对应的唯一 CSS 属性。
来源: https://w3c.github.io/editing/execCommand.html#assorted-inline-formatting-command-algorithms
以下是来自同一规范的上标/下标实际算法:
- 设受下标影响为 affected by subscript,受上标影响为 affected by superscript,两个布尔变量均初始为 false。
当节点是内联节点时:
注意:Firefox 6.0a2 忽略 vertical-align 的作用,只关心 <sub> 和 <sup> 标签本身。Opera 11.11 类似,实际上即使对于像粗体这样的命令也是如此。规范最初遵循 Chrome 14 dev,主要是因为 WebKit 本身将生成带有 vertical-align sub 或 super 的 span,我们希望正确处理它们。但是,Ryosuke 告诉我这里 WebKit 的行为被视为错误,所以我将其更改为与 Gecko/Opera 匹配。
如果节点是下标,则将 affected by subscript 设置为 true。 <- 这是 Chrome/Webkit 表现不正确的地方。
否则,如果节点是上标,则将 affected by superscript 设置为 true。将节点设置为其父节点。如果 affected by subscript 和 affected by superscript 都为 true,则返回字符串 "mixed"。如果 affected by subscript 为 true,则返回 "subscript"。如果 affected by superscript 为 true,则返回 "superscript"。返回 null。
目前的解决方案是1)不要调整样式,或者更确切地说2)自己进行检查。