操作元素之开关灯

分析:

   点击按钮,设置浏览器窗口背景的颜色变化。

效果:

效果图

代码:

 1 <!DOCTYPE html>
 2 <html lang="en">
 3     <head>
 4         <meta charset="UTF-8">
 5         <title>开关灯案例</title>
 6         <style>
 7             *{
 8                 margin: 0;
 9                 padding: 0;
10             }
11             div{
12                 position: absolute;     /*设置绝对定位+高度100%,可以使div高度等于浏览器窗口的高度*/
13                 width: 100%;
14                 height: 100%;
15                 background-color: white;
16             }
17             button{
18                 width: 80px;
19                 height: 40px;
20                 margin: 10px 0 0 10px;
21             }
22         </style>
23     </head>
24     <body>
25         <div>
26             <button>开关灯</button>
27         </div>
28         <script>
29             var box=document.querySelector("div");
30             var btn=document.querySelector("button");
31 
32             btn.onclick=function(){
33                 if(box.style.backgroundColor==="white"){
34                     box.style.backgroundColor="black";
35                 }else{
36                     box.style.backgroundColor="white";
37                 }
38             }
39         </script>
40     </body>
41 </html>

  这个练习我自己学到的一点就是怎么让div的高度设置的和浏览器窗口一样高,设置div为绝对定位,然后再设置高度是100%即可完成。另外,前面一个练习(博客里面没放)想让一个子div在父div里面上下居中,研究了半天最后还是靠百度,把父元素设置成相对定位,子元素设置成绝对定位,另外父div的高度和行高设置成一样大小,即可完成。

猜你喜欢

转载自www.cnblogs.com/cy1227/p/12158937.html