首先都需要建一个css文件夹,里面存放不同颜色的css文件:blue.css; red.css; yellow.css; green.css 在这几个文件中分别写好要改变的样式。
接下来就是html文件,首先第一种思路:只写一个link标签(不推荐,原因请继续阅读)。代码如下:
1 index.html -->
2 head >
3 meta charset ="UTF-8" >
4 title > 动态换肤 title >
5 link rel ="stylesheet" type ="text/css" href ="css/blue.css" >
6 style >
7 * { margin : 0 ; padding : 0 ; }
8 div {
9 height : 50px ;
10 background-color : black ;
11 padding-left : 10px ;
12 }
13 div section {
14 width : 30px ;
15 height : 30px ;
16 margin : 10px ;
17 display : inline-block ;
18 }
19 div section:nth-of-type(1) {
20 background-color : red ;
21 }
22 div section:nth-of-type(2) {
23 background-color : blue ;
24 }
25 div section:nth-of-type(3) {
26 background-color : green ;
27 }
28 div section:nth-child(4) {
29 background-color : yellow ;
30 }
31 style >
32 head >
33 body >
34 div >
35 section data-color ="red" > section >
36 section data-color ="blue" > section >
37 section data-color ="green" > section >
38 section data-color ="yellow" > section >
39 div >
40 script >
41 var div = document.getElementsByTagName( " div " )[ 0 ];
42 // 添加鼠标单击事件
43 div.onclick = function (event){
44 console.log(event.target);
45 var ele = event.target;
46 console.log(ele.tagName); // 使用.tagName时,控制台 输出全部大写,所以在下面的if判断中,使用[SECTION].
47 if (ele.tagName == ' SECTION ' ){
48 var color = ele.dataset.color;
49 // var color = ele.getAttribute("data-color");
50 var link = document.createElement( " link " );
51 link.href = ' css/ ' + color + " .css " ;
52 link.rel = " stylesheet " ;
53 // 添加样式表到head,但是会造成页面样式表越来越多,所以不推荐
54 document.head.appendChild(link);
55 }
56 }
57 script >
58 body >
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://haodehen.cn/did101657