Quantcast
Channel: mattintosh note
Viewing all articles
Browse latest Browse all 891

JavaScript の style.cssText と style.styleProperty

$
0
0

style.cssTextstyle.stylePropertyがよくわかってなかったのでメモ。

style.cssTextで書いた場合はもともとあった style属性を一新する。下の例で言うと color: redはなくなり、text-decoration: underlineのみが有効になる。

var e = document.getElementById("body");
e.style.cssText = "color: red";
e.style.cssText = "text-decoration: underline";

style.cssTextで追記する場合は以下のような方法が使える。

var e = document.getElementById("body");
e.style.cssText  = "color: red";
e.style.cssText += "text-decoration: underline";
var e = document.getElementById("body");
e.style.cssText = "color: red";
e.style.cssText = e.style.cssText + "text-decoration: underline";

style.stylePropertyの場合は style属性の内容に追加し、そのプロパティが既に存在する場合は置き換える。

var e = document.getElementById("body");
e.style.color = "red";
e.style.textDecoration = "underline";

!importantの指定は style.stylePropertyでは出来ない(?)ので style.cssTextで行う。


sheet.insertRuleを使う場合は stylesheet.style.cssTextなんかとごっちゃになるのでこちらもメモ。insertRuleではなく cssTextで一気に追加することもできるようだ(ただし、上記のように毎回リセット)。

var e = document.createElement("style");
document.head.appendChild(e);
e.sheet.insertRule("p { font-family: monospace; }", 0);
e.sheet.insertRule("p { color: gray; }", e.sheet.cssRules.length);
document.body.appendChild(
    document.createElement("p").appendChild(
        document.createTextNode(e.sheet.cssRules.length)
    )
);

システム側で強制的に挿入される <style>要素のルールを全て削除する場合は .sheet.deleteRule(index)でいいのかな…。

var e = document.getElementsByTagName("style");
for (var i = 0; e[i] != null; i++) {while (e[i].sheet.deleteRule(0));
}

IEで試したときに .cssText = "";で一括削除出来たような気がするけど、document.getElementsByTagName("style")document.styleSheets使ってたかどうか覚えてないんだよな…。

上の方法だと無限ループになりそうだから下の方法で要素ごと消すほうが楽そうだ。

var e = document.getElementsByTagName("style");
while (e[0]) {
    e[0].parentElement.removeChild(e[0]);
}

Viewing all articles
Browse latest Browse all 891

Trending Articles