IEのDOM.prototypeエミュレーション(lte 7)

誰もが知っているように、8より下の「高価な」IEバージョンでは、Element.prototype(およびHTMLElement、Node)のサポートはありません。





開始するには、単にElement関数を作成し、プロトタイプを通して必要な関数を追加します。

Element = function () {};

Element.prototype.pSib = function () {

var node = this ;

while (node = node.previousSibling) {

if (node.nodeType != 3) return node;

}

return null ;

}




この関数は、テキストノードをスキップして、要素のpreviousSiblingを検索します!



behaviorを使用してパブリックメソッドを作成します。

< PUBLIC:COMPONENT >

< PUBLIC:METHOD NAME ="pSib"

INTERNALNAME ="_pSib" />

< script type ="text/javascript" >

var el = new Element;

_pSib = el.pSib;

</ script >

</ PUBLIC:COMPONENT >






test.htcに保存し、コメントを介してブラウザーに追加します。

<!--[if lte IE 7]>

<style type="text/css">

* { behavior: url(test.htc); }

</style>

<![endif]-->








次に、 createElementを拡張し、動作で宣言したメソッドを各要素に割り当てます。

var __IEcreateElement = document .createElement;

document .createElement = function (tagName) {

var element = __IEcreateElement(tagName);

var interface = new Element;

for (method in interface )

element[method] = interface [method];

return element;

}








ソースコードは次のようになります。

<! DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" >

< html xmlns ="http://www.w3.org/1999/xhtml" >

< head >

< title > IE.prototype </ title >

< meta http-equiv ="content-type" content ="text/html; charset=windows-1251" />



<!--[if lte IE 7]>

<script type="text/javascript">

Element = function () {};

var __IEcreateElement = document.createElement;

document.createElement = function (tagName) {

var element = __IEcreateElement(tagName);

var interface = new Element;

for (method in interface)

element[method] = interface[method];

return element;

}

</script>

<style type="text/css">

* { behavior: url(test.htc); }

</style>

<![endif]-->



<script type= "text/javascript" >

function addLoadEvent(func) {

var oldonload = window.onload;

if ( typeof window.onload != 'function' ) { window.onload = func;}

else {window.onload = function () { if (oldonload) {oldonload();}func();}}

}



Element.prototype.pSib = function () {

var node = this ;

while (node = node.previousSibling) {

if (node.nodeType != 3) return node;

}

return null ;

}



addLoadEvent( function () {

alert( document .getElementById( 'testinput' ).pSib().id);

});

</ script >

</ head >

< body >

< label for ="text" id ="testlabel" > Enter text </ label >

< input name ="text" type ="text" id ="testinput" >

</ body >

</ html >


* This source code was highlighted with Source Code Highlighter .




addLoadEventは、ページが100%読み込まれた後にコードを実行します。



Element.prototypeは他のブラウザでも正常に動作することを忘れないでください。したがって、コメントに移動する必要はありません;)



簡単なデモを見る




All Articles