CSSの!important
は極力使いたくないのですが
使わざるを得ないケースが有ります。
// javascript $('#hoge').css('width', '900px !important');
の様に記述してもスタイルそのものが付きませんでした。
どうやら
// javascript $('#hoge').css('cssText', 'width: 900px !important');
こんな感じでcssText
というプロパティを使用すれば設定できるようです。
ただ、cssText
でスタイルをつけると、それまでにその要素についていたスタイルがまるっと置き換わってしまうます(öДö *)
例えば、下の様なhtmlがあったとして上記のjsを実行すると。。。
<div id="hoge" style="color: #F00;">hoge</div>
↓ jsを実行!
<div id="hoge" style="width: 900px !important;">hoge</div>
なので、元のDOMにスタイルがある場合は前もって元のスタイルをattr
などでとっておくのが良さそうです。
<div id="hoge" style="color: #F00;">hoge</div>
// javascript var $hoge = $('#hoge'); // 元のスタイルを取っておく var style = $hoge.attr('style'); // important付きのstyleをつける $hoge.css('cssText', 'width: 900px !important;' + style);
新しく付けたいプロパティと同じプロパティが既に付いている場合、
!important
付きのプロパティ場合は!important
のプロパティが適応されましたが、
!important
がないプロパティ場合は元のプロパティが残りました。
<div id="hoge" style="color: #F00; width:100px;">hoge</div> <div id="fuga" style="color: #00F; width:100px;">fuga</div>
// javascript // !important付き var $hoge = $('#hoge'); var hogeStyle = $hoge.attr('style'); $hoge.css('cssText', 'width: 900px !important;' + hogeStyle); console.log($hoge[0]); // 出力結果 ↓ // <div id="hoge" style="color: #F00; width: 900px !important;">hoge</div> // !important無し var $fuga = $('#fuga'); var fugaStyle = $fuga.attr('style'); $fuga.css('cssText', 'width: 900px' + fugaStyle); console.log($fuga[0]); // 出力結果 ↓ // <div id="fuga" style="color: #00F; width: 100px;">fuga</div>
CSSの強い順、後から付けた順で適応されるっぽいっぽいなので、
元のスタイルを先にして追加するようにすれば間違いなさそうです。
<div id="fuga" style="color: #00F; width:100px;">fuga</div>
// javascript var $fuga = $('#fuga'); var style = $fuga.attr('style'); $fuga.css('cssText', style + ';width: 900px'); console.log($fuga[0]); // 出力結果 ↓ // <div id="fuga" style="color: #00F; width: 900px;">hoge</div>
だーけーどー、
!important
を使わない場合は、こんなメンドーな事せずに
素直に$fuga.css('width', '900px')
で追加するのが良いと思います。
cssText
を使わなくても
// javascript $hoge.attr('style', 'width: 900px !important;');
の様にattr
を使ってもimportant付きのcssを付けることが出来るようです。
この場合も、cssText
の時と同じで、まるっとstyle置き換わっちゃいますが...
参考
jQueryでCSSの「!important」宣言の扱い方 | BlackFlag
#2066 (.css({height: "300px !important"})) – jQuery Core - Bug Tracker