TA的每日心情 | 开心 2021-12-13 21:45 |
---|
签到天数: 15 天 [LV.4]偶尔看看III
|
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>
复制代码
|
|