1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="utf-8"> 5 <title>javascript中控制类名className 属性title> 6 <style type="text/css"> 7 input{ 8 font-size: 12px; 9 }10 .beijing{11 background-color: #4682B4;12 color: #FFFFFF;13 }14 .guoqing{15 font-size: 20x;16 font-weight: bold;17 }18 style>19 head>20 <body>21 <div id="con" class="beijing">今年国庆想去北京看一看div>22 <form action="" method="post">23 <input type="button" name="" id="" value="点击控制" onclick="rec()"/>24 form>25 <script type="text/javascript">26 var mychar=document.getElementById('con');27 document.write('此时div的clas的属性值'+mychar.className)//输出clas属性28 function rec(){29 mychar.className='guoqing';//改变class类名30 // var myrec=confirm('北京天安门怎么样');31 // if(myrec==true){32 // document.write('是的,我想去');33 // }else{34 // document.write('你了,国庆怎么干嘛');35 // }36 }37 script>38 body>39 html>
className 属性设置或返回元素的class 属性,语法为//object.className = classname;
"控制类名className属性"作用:1.获取元素的class 属性2. 为网页内的某个元素指定一个css样式来更改该元素的外观
测试:通过className属性来设置元素的样式:
1.给id="p1"元素通过className添加"类名为one"的样式。当点击"添加样式"按钮,第一段文字添加样式。
2.给id="p2"元素通过className修改为"类名为two"的样式。当点击"更改外观"按钮,第二段文字更改样式。
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> 5 <title>className属性title> 6 <style> 7 body{ font-size:16px;} 8 .one{ 9 border:1px solid #eee;10 width:230px;11 height:50px;12 background:#ccc;13 color:red;14 }15 .two{16 border:1px solid #ccc;17 width:230px;18 height:50px;19 background:#9CF;20 color:blue;21 }22 style>23 head>24 <body>25 <p id="p1" > JavaScript使网页显示动态效果并实现与用户交互功能。p>26 <input type="button" value="添加样式" onclick="add()"/>27 <p id="p2" class="one">JavaScript使网页显示动态效果并实现与用户交互功能。p>28 <input type="button" value="更改外观" onclick="modify()"/>29 30 <script type="text/javascript">31 function add(){32 var p1 = document.getElementById("p1");33 p1.className="one";34 }35 function modify(){36 var p2 = document.getElementById("p2");37 p2.className="two";38 }39 script>40 body>41 html>
Copyright © 2004-2024 Ynicp.com 版权所有 法律顾问:建纬(昆明)律师事务所 昆明市网翼通科技有限公司 滇ICP备08002592号-4