DOM Using getStyle
一見、DOM Using getXYのサンプルと同じにみえるが、こちらのサンプルでは、大きいほうの矩形(赤)のスタイルから、背景色(赤い)取得し(この際にgetStyle()を用いる)、小さい法の矩形(青)の背景色に適用する。
このサンプルページにも
One of the benefits of this method is that it can retrieve either inline styles or styles set in a stylesheet. Browsers have different methods for retrieveing styles from a stylesheet, but the getStyle method normalizes these for you.
(以下、訳文)
このメソッド(getStyle())は、インラインスタイル(タグに直接かかれるスタイル)と、スタイルシートに定義されているスタイルの両方に利用できる。
スタイルシートに定義されたスタイルを取得するのは、ブラウザーごとにことなった方法が必要なので、getStyleは、これらを標準化する。
とかかれている。クロスブラウザー対応という奴のことですね。
サンプルコードは以下。
<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; height:10px; width:10px; } #bar { width:100px; height:100px; background-color:#f00; margin:0 0 1em 100px; } </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="bar"のスタイルのうちの背景色(backgroundColorを取得) var setBgColor = function() { // id="bar"のスタイルのうちの背景色(backgroundColor)を取得 var bgcolor = YAHOO.util.Dom.getStyle('bar', 'backgroundColor'); // id="foo"のスタイルのうちの背景色をそれに設定 YAHOO.util.Dom.setStyle('foo', 'backgroundColor', bgcolor); }; // id=demo-runのクリックイベントのハンドラとしてfade(上で定義)を設定。 YAHOO.util.Event.on('demo-run', 'click', setBgColor); } </script> </HEAD> <BODY onload=init()> <div id="foo"></div> <div id="bar"></div> <button id="demo-run">実行</button> </BODY> </HTML>
実行前の画面は以下。
実行すると以下のようになる。