あなたはすべての主要なブラウザでは、現在の選択範囲の色やフォントサイズを取得するためにdocument.queryCommandValue()
を使用することができますブラウザ間で一貫性がなく、FontSize
コマンドは、CSSではなくHTML <font>
要素で使用されるフォントサイズ1〜7でのみ動作します。したがって、要素co選択をntainingとwindow.getComputedStyle()
/currentStyle
を使用して、そのCSSプロパティを調べる:
ライブデモ:http://jsfiddle.net/timdown/K4n2j/
コード:
function getComputedStyleProperty(el, propName) {
if (window.getComputedStyle) {
return window.getComputedStyle(el, null)[propName];
} else if (el.currentStyle) {
return el.currentStyle[propName];
}
}
function reportColourAndFontSize() {
var containerEl, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
containerEl = sel.getRangeAt(0).commonAncestorContainer;
// Make sure we have an element rather than a text node
if (containerEl.nodeType == 3) {
containerEl = containerEl.parentNode;
}
}
} else if ((sel = document.selection) && sel.type != "Control") {
containerEl = sel.createRange().parentElement();
}
if (containerEl) {
var fontSize = getComputedStyleProperty(containerEl, "fontSize");
var colour = getComputedStyleProperty(containerEl, "color");
alert("Colour: " + colour + ", font size: " + fontSize);
}
}
これが改善されているが、そのような単位が異なるかのように、ブラウザの不整合が残っていますカラーフォーマット。
私は、すべてのブラウザとIE7,8の新しいバージョンのfont-sizeプロパティのユニットでいくつかの問題に気づいていませんでした。しかし、色はrgbと16進表記のどこかで解釈されます。しかし、それはまだ私のための問題ではない、おそらく私はそれのためのいくつかの条件を作成します。ありがとうございました! – optimista
選択肢に複数のフォントサイズ(または色)が含まれていると「未定義」になることはありますか?すべてを選択すると、「Color:rgb(0、0、0)、font size:16px」という警告が表示されます。これは私の目的のために混乱しています。 –
@Timo:選択の親要素はあなたの考えではない可能性があります。あなたがすべてを選択すると、それは彼がcontenteditable要素である可能性が高くなります。これはスタイリングを持たないかもしれません。 –