原生 JS 綁定 focus/blur 事件,在 IE 中報錯:type 為空或不是對象、border 無法移除。
| 標準瀏覽器 | IE (≤8/兼容模式) |
|---|---|
事件對象傳參 e | 全局 window.event |
目標元素 e.target | e.srcElement |
移除樣式 removeProperty | 不支持,需用 style.cssText = '' 或覆蓋屬性 |
function handleFocusEvent(e) {
e = e || window.event;
var target = e.srcElement || e.target;
if (e.type === "focus") {
target.style.backgroundColor = "lightgray";
target.style.border = "thick solid red";
} else {
// IE 不支持 removeProperty,直接清空 cssText 或單獨覆蓋
target.style.cssText = ''; // 核暴力但有效
target.style.border = "thick solid black";
}
}
addEventListener / attachEvent 統一綁定,避免內聯 onfocus 污染全局。eventlistener)或直接放棄 IE 老版本支持。classList.toggle),減少行內樣式操作。IE 事件模型與標準差異大,封裝兼容層或使用成熟庫(jQuery 等)是工程化解法。