欢迎来到代码驿站!

JavaScript代码

当前位置:首页 > 网页前端 > JavaScript代码

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

时间:2021-05-18 09:47:57|栏目:JavaScript代码|点击:

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>

上一篇:JavaScript实现动态删除列表框值的方法

栏    目:JavaScript代码

下一篇:一个不错的可以检测多中浏览器的函数和其它功能第1/2页

本文标题:js改变style样式和css样式的简单实例

本文地址:http://www.codeinn.net/misctech/124032.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有