六帖のかたすみ

DVを受けていた男性。家を脱出して二周目の人生を生きています。自閉症スペクトラム(受動型)です。http://rokujo.org/ に引っ越しました。

jQuery: CSSプロパティのセットは非推奨!?

jQueryの公式ガイドを読んでいたらちょっとびっくりする記述がありました。

 

learn.jquery.com

// Setting CSS properties.
 
$( "h1" ).css( "fontSize", "100px" ); // Setting an individual property.
 
// Setting multiple properties.
$( "h1" ).css({
fontSize: "100px",
color: "red"
});

 jQueryではこんな風に簡単にCSSのプロパティを変更して表示を変えることができるのだけど、お勧めしないと書いてあります。

However, it should generally be avoided as a setter in production-ready code, because it's generally best to keep presentational information out of JavaScript code.  

適当訳:「しかし、製品用のコードでsetterを使うのはふつう避けられるべきです。なぜなら一般的に、プレゼンテーション情報はJavaScriptコードの外側に書くのが良いからです。」

というわけで、setterでCSSを直接変更するのはやめて、あらかじめCSSに変更したいプロパティを書いておいて、classを変更することで対処せよと書いてあります。明日この機能を使うつもりだったので、読んでおいて正解でした。下の例なら .big にfont-size: 100px; などを設定しておけばいいですね。

Instead, write CSS rules for classes that describe the various visual states, and then change the class on the element.
 
// Working with classes.
 
var h1 = $( "h1" );
 
h1.addClass( "big" );
h1.removeClass( "big" );
h1.toggleClass( "big" );
 
if ( h1.hasClass( "big" ) ) {
...
}