方法1: 適用IE9及其他非IE瀏覽器
obj.style.setProperty("background-color", "green");
obj.style.getPropertyValue("background-color");
obj.style.removeProperty("background-color");
方法2: 適用IE系列
obj.style.setAttribute("backgroundColor", "green");
obj.style.getAttribute("backgroundColor");
obj.style.removeAttribute("backgroundColor");
加上判斷瀏覽器類別,就一次搞定了
<html>
<head>
<script type="text/javascript">
function testMethod() {
var browser=navigator.userAgent;
var myDiv=document.getElementById("myDiv");
if(browser.search("MSIE")>-1){
alert(myDiv.style.getAttribute("backgroundColor"));
myDiv.style.removeAttribute("backgroundColor");
myDiv.style.setAttribute("backgroundColor", "green");
alert(myDiv.style.getAttribute("backgroundColor"));
}else{
alert(myDiv.style.getPropertyValue("background-color"));
myDiv.style.removeProperty("background-color");
myDiv.style.setProperty("background-color", "green");
alert(myDiv.style.getPropertyValue("background-color"));
}
}
</script>
</head>
<body>
<div id="myDiv" style="background-color: red; height: 50px; width: 50px"></div><br />
<input type="button" value="T E S T" onclick="testMethod()" />
</body>
</html>
參考資料:Style handling methods in JavaScript