网页换肤,通过调用不同的样式来实现换肤的效果,前面看过用jq来实现换肤的效果,原理一样,今天记录的是用原生javascript实现换肤的效果。
首先,html结构,添加4个颜色按钮:
1 <ul>
2 <li id="red" class="current">红色</li>
3 <li id="yellow">黄色</li>
4 <li id="blue">蓝色</li>
5 <li id="green">绿色</li>
6 </ul>
接下来为html添加外链样式,默认为红色,通过改变链接的href属性值,实现换肤效果。
<link rel="stylesheet" href="red.css" />
最后写函数方法给每个颜色按钮添加单击事件,将网页换肤。
1 window.onload=function(){
2 var oSkin=document.getElementsByTagName('li');
3 var oLink=document.getElementsByTagName('link')[0];
4 for(var i=0; i<oSkin.length; i++){
5 oSkin[i].onclick=function(){
6 for(var p in oSkin)
7 oSkin[p].className="";
8 this.className="current";
9 oLink['href']=this.id+".css";
10 }
11 }
12 }
在这里,我一共写了5个样式,其中4个是不同肤色的样式,还有一个common的样式。
1 common.css8 red.css
2 ul li{width:15px; height:15px; border:3px solid #fff; display:inline; float:left; text-indent:-300em; margin:0px 10px; }
3 ul li.current{ border-color:#666;}
4 #red{background:red;}
5 #yellow{ background:yellow;}
6 #blue{ background:blue;}
7 #green{ background:green;}
9 body{ background:red;} 10 blue.css
11 body{ background:blue;} 12 yellow.css
13 body{ background:yellow;}
14 green.css
15 body{ background:green;}
简单的换肤效果完成了。