DOM Using setStyle
青い矩形の透過度を0.5(50%)に設定するサンプル。
先にやったものとほぼ同じである。
ソースコードを除いてみると、styleの設定に関して、次のような但し書きがかいてある。
/*margin and padding on body element can introduce errors in determining element position and are not recommended; we turn them off as a foundation for YUI CSS treatments. */ /* (訳) body部のマージンとパディングの設定は要素(element)の位置を決める のにエラーの原因となることが多いので非推奨。 YUIのCSSでは、これをともに0に設定するのを基本にしている */
これは、CSSの参考書にもよく書かれていることなのだが、肝に命じておこう。
このサンプルの説明には、setStyleはブラウザーごとの設定の方法の違いを吸収して、シンプルに使えるようになっていると書かれている。
opacity(透過度)は、styleの中でもその代表的なもの(Safari2までは不採用、Operaも8まで不採用、IEとMozillaでは設定のやり方が異なる)なので、例として取り上げられているのだろう。
サンプルコードは以下。
<HTML> <HEAD> <META http-equiv="Content-Type" content="text/html; charset=UTF-8"> <META http-equiv="Content-Style-Type" content="text/css"> <TITLE>Ajax_Sampling</TITLE> <!-- #style で id=foo,barの全ての要素に適用する。 --> <style type="text/css"> /*margin and padding on body element can introduce errors in determining element position and are not recommended; we turn them off as a foundation for YUI CSS treatments. */ /* (訳) body部のマージンとパディングの設定は要素(element)の位置を決める のにエラーの原因となることが多いので非推奨。 YUIのCSSでは、これをともに0に設定するのを基本にしている */ body { margin:0; padding:0; } #foo { background-color:#00f; color:#fff; height:100px; width:100px; margin-bottom:1em; } </style> <!-- 読み込むjs --> <script type="text/javascript" src="scripts/yui/yahoo/yahoo-min.js" > </script> <script type="text/javascript" src="scripts/yui/dom/dom-min.js" > </script> <script type="text/javascript" src="scripts/yui/event/event-min.js" > </script> <script type="text/javascript"> init = function() { // id=fooの透過度を0.5に設定する。 var fade = function() { YAHOO.util.Dom.setStyle('foo', 'opacity', 0.5); }; // id=demo-runのクリックイベントのハンドラとしてfade(上で定義)を設定。 YAHOO.util.Event.on('demo-run', 'click', fade); } </script> </HEAD> <BODY onload=init()> <div id="foo">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</div> <button id="demo-run">実行</button> </BODY> </HTML>
実行前の画面は以下。
実行すると、透過度が50%になる。