js改变style样式和css样式的简单实例
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>
相关推荐
NARUTOLUOLUO 2020-08-03
jiedinghui 2020-10-25
Ladyseven 2020-10-22
zuncle 2020-09-28
xiaohuli 2020-09-02
葉無聞 2020-09-01
nicepainkiller 2020-08-20
AlisaClass 2020-08-09
myloveqiqi 2020-08-09
buttonChan 2020-08-02
drdrsky 2020-07-29
Ladyseven 2020-07-25
nicepainkiller 2020-07-24
AlisaClass 2020-07-19
hellowzm 2020-07-19
background-color: blue;background-color: yellow;<input type="button" value="变蓝" @click="changeColorT
昔人已老 2020-07-19
骆驼的自白 2020-07-18
lanzhusiyu 2020-07-19
hellowzm 2020-07-19