本文分享JavaScript動態設置樣式style的方法,供有需要的朋友參考。具體分析如下:
動態修改style時有幾個易錯點:
1. 修改元素的樣式類不是設置class屬性,而是className屬性。
2. 單獨修改樣式的屬性使用"style.屬性名"。注意CSS中的屬性名在JavaScript中操作時可能不一樣,主要集中在那些含"-"的屬性,因為JavaScript中"-"不能做屬性名。例如CSS中的background-color在JS中是style.background;CSS中的font-size在JS中是style.fontSize;margin-top則是style.marginTop。
3. 單獨修改控件的樣式,例如<input type="button" value="AAA" onclick="this.style.color='red'" />。
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>動態修改style</title>
<style type="text/css">
.day { background-color:Green; }
.night { background-color:Black; }
</style>
<script type="text/javascript">
function dayclick() {\br /> var divMain = document.getElementById("divMain");
divMain.className = "day"; // 注意這裡用的是className而不是class
}
function nightclick() {\br /> var divMain = document.getElementById("divMain");
divMain.className = "night";
}
</script>
</head>
<body>
<div id="divMain" class="day">
<font color="red">中華人民共和國</font>
</div>
<input type="button" value="白天" onclick="dayclick()" />
<input type="button" value="黑夜" onclick="nightclick()" />
</body>
</html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
.day { background-color:White; }
.night { background-color:Black; }
</style>
<script type="text/javascript">
function switchLight() {\br /> var btnSwitch = document.getElementById("btnSwitch");
if (document.body.className == "day") { document.body.className = "night"; btnSwitch.value = "開燈"; }\br /> else { document.body.className = "day"; btnSwitch.value = "關燈"; }
}
</script>
</head>
<body class="night">
<input type="button" value="開燈" id="btnSwitch" onclick="switchLight()"/>
</body>
</html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>動態設置style練習(修改文本框背景色)</title>
<script type="text/javascript">
function IniEvents() {
var inputs = document.getElementsByTagName("input");
for (var i = 0; i < inputs.length; i++) {\br /> if (inputs[i].type == "text") { inputs[i].onblur = txtOnBlur; }
}
}
function txtOnBlur() {
// txtOnBlur是onblur的響應函數,可以用this取得發生事件控件的對象
if (this.value.length <= 0) { this.style.background = "red"; }\br /> else { this.style.background = "white"; }\br /> }
</script>
</head>
<body onload="IniEvents()">
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
</body>
</html>
希望本文所述對大家的JavaScript程序設計有所幫助。