Simple example of js changing style style and css style

  • 2021-07-01 06:22:52
  • OfStack

js can realize the user's selection conditions in the page to change the style in the page. The page style can be modified by style or css. First, look at js to change style style. The code is as follows:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <title>Change.html</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  
  <!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
 <script language="javascript">
   function test4(event) {
	  if(event.value == " Black ") {
	   // Get div1
	   var div1 = document.getElementById('div1');
	   div1.style.backgroundColor="black";
	  }
	  if(event.value == " Red ") {
	   // Get div1
	   var div1 = document.getElementById('div1');
	   div1.style.backgroundColor="red";
	  }
	 }
 </script>
</head>
<body>
 <div id="div1" style="width:400px; height:300px; background-color:red;">div1</div>
 <input type="button" value=" Black " onclick="test4(this)"/>
 <input type="button" value=" Red " onclick="test4(this)"/>

 </body>
</html>

test4 (this) represents the current < input is equivalent to treating it as an object.

Let's look at changing the css style under 1. The code is as follows:


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
 <head>
  <title>Change1.html</title>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  
  <link rel="stylesheet" type="text/css" href="css/Change.css">
 <script language="javascript">
   function test4(event) {
	 // Gets all of the class Selectors all get 
	 var ocssRules = document.styleSheets[0].rules;
	 // From ocssRules Take out what you want class
	 var style1 = ocssRules[0];
	 if(event.value == " Black ") {
	   //window.alert(style1.style.backgroundColor);
	   style1.style.backgroundColor="black";
	 }else if(event.value == " Red ") {
	   style1.style.backgroundColor="red";
	 }
	 
	 }
  </script>
</head>
<body>
 <div id="div1" class="style1">div1</div>
 <input type="button" value=" Black " onclick="test4(this)"/>
 <input type="button" value=" Red " onclick="test4(this)"/>

 </body>
</html>

Related articles: