本文實例講述了javascript動態設置樣式style的方法。分享給大家供大家參考。具體分析如下:
動態修改style
1.易錯:修改元素的樣式不是設置class屬性,而是className屬性.
2.易錯:單獨修改樣式的屬性使用"style.屬性名".注意在css中屬性名在javascript中
操作的時候屬性名可能不一樣,主要集中在那些屬性名中含有-的屬性,因為
javascript中-是不能做屬性,類名的。所以在CSS中背景色是background-clolor,而javascript中則是style.background;元素樣式名是class,在javascript中是className屬性;font-size->style.fontSize;margin-top->style.marginTop
3.單獨修改控件的樣式<input type="button" value="AAA" onclick="this.style.color='red'" />
1.舉例1
<html xmlns="http://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() {
var divMain = document.getElementById("divMain");
//注意這裡使用的是className而不是class
divMain.className = "day";
}
function nightclick() {
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>
2. 示例:動態修改style(模擬開燈,關燈)
<html xmlns="http://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() {
var btnSwitch = document.getElementById("btnSwitch");
if (document.body.className == "day") {
document.body.className = "night";
btnSwitch.value = "開燈";
}
else {
document.body.className = "day";
btnSwitch.value = "關燈";
}
}
</script>
</head>
<body class="night">
<input type="button" value="開燈" id="btnSwitch" onclick="switchLight()"/>
</body>
</html>
3. 示例:
<html xmlns="http://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++) {
if (inputs[i].type == "text") {
//設置txtOnBlur函數為input元素的onblur事件的響應函數
inputs[i].onblur = txtOnBlur;
}
}
}
function txtOnBlur() {
/*
txtOnBlur是onblur的響應函數,而不是被響應函數調用
的函數,所有可以用this來取的發生事件控件的對象
*/
if (this.value.length <= 0) {
this.style.background = "red";
}
else {
this.style.background = "white";
}
}
</script>
</head>
<body onload="IniEvents()">
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
<input type="text" /><br />
</body>
</html>
希望本文所述對大家的javascript程序設計有所幫助。