JS实现网页换肤
概述:
通过点击按钮,为页面切换不同的背景色;
原理:
通过给link的href设置不同的值实现,皮肤的更换;
Code
JS
/*
* 点击按钮切换页面的皮肤
* @param obj 按钮组
* @param aSkin 皮肤组合
* @param oSkin 设置皮肤的link标签
*/
functionchangeSkin(obj,aSkin,oSkin) {
for(var i =0;i < obj.length;i++) {
obj[i].index= i;
obj[i].onclick=function() {
var_this =this;
for(var j in aSkin) {
obj[j].className='';
}
_this.classList.add('active');
oSkin.setAttribute('href',aSkin[_this.index]);
};
}
}
案例
HTML
<link rel="stylesheet" href="../CSS/skin1.css" id="skin1">
<div class="list">
<a href="javascript:;"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
</div>
CSS
body,div{padding:0;margin:0;}
.list{width:300px;margin:30px auto;}
.list a{position:relative;display:inline-block;list-style:none outside none;text-decoration:none;width:20px;height:20px;margin-right:10px;}
a:nth-child(1) {background:palevioletred;}
a:nth-child(2) {background-color:lightblue;}
a:nth-child(3) {background-color:bisque;}
a:nth-child(4) {background-color:brown;}
.list a.active:before{content:'';position:absolute;top:4px;left:4px;width:12px;height:12px;background-color:#fff;z-index:10;}
JS
window.onload=function() {
var oSkin =document.getElementById('skin');
var aLink =document.getElementsByTagName('a');
var skin = ['../CSS/skin1.css','../CSS/skin2.css','../CSS/skin3.css','../CSS/skin4.css'];
changeSkin(aLink,skin,oSkin);
};
效果
网页换肤案例效果