1つの可能性は、 attachEvent
がIE-特定。 attachEventListener
を他の多くの方法で使用する必要がありますブラウザ。
現在のブラウザに「適切な」方法を使用するには、それらの機能を検出する必要があります( MDNから抜粋):
if (el.addEventListener){
el.addEventListener('click', modifyText, false);
} else if (el.attachEvent){
el.attachEvent('onclick', modifyText);
}
これを支援する関数を作成することもできます:
function bindEvent(element, type, listener) {
if (element.addEventListener) {
element.addEventListener(type, listener, false);
} else if (element.attachEvent) {
element.attachEvent('on' + type, listener);
}
}
次に、これらの2行の代わりに:
divholders[i].attachEvent('onmouseover', (function(i) { return function() { divholders[i].style.backgroundColor='#266699'; }; })(i));
divholders[i].attachEvent('onmouseout', (function (i) { return function() { divholders[i].style.backgroundColor = '#F5F5F5'; }; })(i));
...関数を使用してハンドラをバインドします(イベント型引数の on
をスキップします)。
(function (i) {
bindEvent(divholders[i], 'mouseover', function() {
divholders[i].style.backgroundColor = '#266699';
});
bindEvent(divholders[i], 'mouseout', function() {
divholders[i].style.backgroundColor = '#F5F5F5';
});
})(i);
You could also just enclose the <div>
:
(function (div, i) {
bindEvent(div, 'mouseover', function() {
div.style.backgroundColor = '#266699';
});
bindEvent(div, 'mouseout', function() {
div.style.backgroundColor = '#F5F5F5';
});
})(divholders[i], i);