- 為什麼在IE中運行這段代碼會提示type為空或不是對象?為什麼border屬性會無法移除?
-
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>example</title>
<style type="text/css">
p{
border: thin solid black;
background: gray;
color: white;
padding: 10px;
margin: 5px;
}
</style>
</head>
<body>
<p>
<label for="fave">fruit:<input id="fave" name="name"/></label>
</p>
<p>
<label for="name">name:<input id="name" name="name"/></label>
</p>
<button type="submit">submit vote</button>
<button type="reset">reset</button>
<script type="text/javascript" defer="true">
function handleFocusEvent(e){
if(e.type=="focus"){//為什麼在IE中運行這段代碼會提示type為空或不是對象?
e.target.style.backgroundColor="lightgray";
e.target.style.border="thick solid red";
}else{
e.target.style.removeProperty("background-color");
e.target.style.border="thick solid black";
// e.targer.style.removeProperty("border")//為什麼border屬性會無法移除?
}
}
var inputElems=document.getElementsByTagName("input");
for(var i=0;i<inputElems.length;i++){
inputElems[i].onfocus=handleFocusEvent;
inputElems[i].onblur=handleFocusEvent;
}
</script>
</body>
</html>
最佳回答:
function handleFocusEvent(e) {
e = e || window.event;//ie事件存儲在window.event中,不是直接傳入函數參數
var o = e.srcElement || e.target;//ie源對象是srcElement,不是target,要做兼容
if (e.type == "focus") {//為什麼在IE中運行這段代碼會提示type為空或不是對象?
o.style.backgroundColor = "lightgray";
o.style.border = "thick solid red";
} else {
o.style.cssText = ''//IE8-不支持style的removeProperty,直接設置cssText清空所有style的內容或者自己替換下cssText對應的屬性
o.style.border = "thick solid black";
// e.targer.style.removeProperty("border")//為什麼border屬性會無法移除?
}
}