DOMに便利メソッドを突っ込む
IE用のgetComputedStyle互換コード書直し
if(!this.getComputedStyle) { getComputedStyle = function(element) { element.getPropertyValue = getComputedStyle.getPropertyValue; return element; }; getComputedStyle.getPropertyValue = function(prop) { prop = prop.replace(/-([a-z])/g, function(){ return arguments[1].toUpperCase(); }); return this.currentStyle[prop]; }; };
あまり代わってないけどこれでも同じ結果が得られる。前のコードはクロージャを使っていてelementを渡していた。僕は勝手に"this"は"element"ではないと勘違いしていたのでこのようになった。加えてcurrentもタイポだったorz...DOMに関数突っ込んだときのthisはエレメント自信をさす。う〜ん。どこで何を勘違いしたんだか…。
クリックする度に10pxずつ大きくなるスクリプト。*1
<html> <body> <div id="foo" style="background-color: #000000;"></div> <script> shell = document.getElementById('foo'); shell.getSize = function() { var w = parseInt(getComputedStyle(this,'').getPropertyValue('width')); var h = parseInt(getComputedStyle(this,'').getPropertyValue('height')); return { w : w, h: h }; }; shell.setSize = function( width, height ) { this.style.width = width + 'px'; this.style.height = height + 'px'; }; shell.onclick = function() { var s = this.getSize(); this.setSize( s.w + 10, s.h + 10 ); }; shell.setSize(100, 100); </script> </body> </html>