Copy the code code as follows:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.day
{
background-color:White;
}
.night
{
background-color:Black
}
</style>
<script language="javascript" type="text/javascript">
function operStyle() {
var divObj = document.getElementById("divContent");
var btnObj = document.getElementById("btnCommit");
if (divObj.className == "day") {
divObj.className = "night";
btnObj.value = "Turn on the light";
} else {
divObj.className = "day";
btnObj.value = "Turn off the lights";
}
}
//Batch modify the style attributes of divs, consisting of multiple styles
//Method 1:
function methodOne() {
var divObj = document.getElementById("divTest");
divObj.style.backgroundColor = "blue";
divObj.style.border = "solid 1px red";
divObj.style.width = "300px";
divObj.style.height = "200px";
divObj.style.backgroundPosition = "center";
}
//Method 2:
function methodTwo() {
var divObj = document.getElementById("divTest");
divObj.style.cssText = "background-color:Blue; border:solid 1px red; width:300px; height:200px; background-position:center";
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="divContent">
<font color="red">I am a div, bah bah bah! </font>
</div>
<input type="button" value="Turn off the lights" id="btnCommit" onclick="operStyle();" />
<br />
<br />
<br />
<br />
<br />
<br />
<br />
<hr />
<h1>Modify the style of divTest and operate multiple attributes</h1>
<div id="divTest" >
<font color="red">Modify the style of divTest</font>
</div>
<input type="button" value="Modify the style of divTest" onclick="methodTwo()" />
</form>
</body>
</html>
When we use js to write css styles, we usually use the following two methods:
Generally, when we use js to set the style of element objects, we will use this form:
Copy the code code as follows:
var element= document.getElementById("id");
element.style.width=”20px”;
element.style.height=”20px”;
element.style.border=”solid 1px red”;
However, the above method has a disadvantage. If there are more styles, there will be a lot of code; and overriding the style of the object through JS is a typical process of destroying the original style and rebuilding it. This destruction and rebuilding will increase the browser's load. overhead.
There is a cssText method in js:
The syntax is: obj.style.cssText("style");
We can modify the above code to:
Copy the code code as follows:
element.style.cssText=”width:20px;height:20px;border:solid 1px red;”;
This writing method can try to avoid multiple reflows of the page and improve page performance.