AutoCAD 3DMAX C语言 Pro/E UG JAVA编程 PHP编程 Maya动画 Matlab应用 Android
Photoshop Word Excel flash VB编程 VC编程 Coreldraw SolidWorks A Designer Unity3D
 首页 > JavaScript

js改变style样式和css样式的简单实例

51自学网 http://www.wanshiok.com
js改变style样式

js可实现用户对页面中的选择条件改变页面中的样式,页面样式可以通过style修饰,也可以通过css修饰,先来看一下js改变style样式,代码如下:

<!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 == "黑色") {	   //获取div1	   var div1 = document.getElementById('div1');	   div1.style.backgroundColor="black";	  }	  if(event.value == "红色") {	   //获取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="黑色" onclick="test4(this)"/> <input type="button" value="红色" onclick="test4(this)"/> </body></html>

test4(this)代表当前的<input相当于把它看成一个对象。

再来看一下改变css样式,代码如下:

<!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) {	 //获取样式表中所有class选择器都获得	 var ocssRules = document.styleSheets[0].rules;	 //从ocssRules中取出你希望的class	 var style1 = ocssRules[0];	 if(event.value == "黑色") {	   //window.alert(style1.style.backgroundColor);	   style1.style.backgroundColor="black";	 }else if(event.value == "红色") {	   style1.style.backgroundColor="red";	 }	 	 }  </script></head><body> <div id="div1" class="style1">div1</div> <input type="button" value="黑色" onclick="test4(this)"/> <input type="button" value="红色" onclick="test4(this)"/> </body></html>

以上就是小编为大家带来的js改变style样式和css样式的简单实例全部内容了,希望大家多多支持wanshiok.com~


js改变style样式  
上一篇:JavaScript中点击事件的写法  下一篇:js改变css样式的三种方法推荐