JavaScript HTML DOM——改变CSS(样式)

  HTML DOM 允许 JavaScript 改变 HTML 元素的样式。

1、改变 HTML 样式

  如需改变 HTML 元素的样式,请使用这个语法:

1 document.getElementById(id).style.property=new style

  举例1(下面的例子会改变 <p> 元素的样式):

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <!--<meta charset="utf-8">-->
 5         <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
 6         <meta http-equiv="Content-Language" content="zh-cn" />
 7         <title>My test page</title>
 8         
 9     </head>
10     
11     <body>
12     
13         <p id="p1">Hello, world!</p>
14         
15         <script>
16             var x = document.getElementById("p1");
17             p1.style.color = "red";
18         </script>
19     </body>
20 </html>

  输出结果:

Hello, world!

  举例2(本例改变了 id="id1" 的 HTML 元素的样式,当用户点击按钮时):

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <!--<meta charset="utf-8">-->
 5         <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
 6         <meta http-equiv="Content-Language" content="zh-cn" />
 7         <title>My test page</title>
 8         
 9     </head>
10     
11     <body>
12     
13         <h1 id="header1">Header 1!</h1>
14         <!--<button type="button" onclick="document.getElementById('header1').style.color='red'">点击这里!</button>-->
15         <button type="button" onclick='document.getElementById("header1").style.color="red"'>点击这里!</button>
16         <script>
17         </script>
18     </body>
19 </html>

  输出结果:

Header 1!

猜你喜欢

转载自www.cnblogs.com/zyjhandsome/p/9787128.html