javascript 案例二(网页换肤)

今日案例,一个简单的网页换肤,即切换样式表。经过上一修改元素样式的案例,这个写得更为轻松了。

css:

<style>
#container{text-align:center;color: #333}
#nav li{display: inline-block; padding: 8px 20px;margin: 0 10px;cursor: pointer;border-radius: 10px;}
.green{background-color: #16977d;}
.blue{background-color: #3c999c;}
.white{background-color: #f4f4f4;}
.content{margin-top: 100px;font-size: 34px}
</style>

分别写了三个样式表:

green.css, blue.css, white.css

html:

<div id=”container”>
<ul id=”nav”>
<li class=”green”>Green</li>
<li class=”blue”>Blue</li>
<li class=”white”>White</li>
</ul>
<h1 class=”content”>Here is test page</h1>
</div>

js:

var themeList = [‘green’,’blue’,’white’]; //将样式表的名称写在数组里
var tarObj=document.getElementById(‘stylefile’); //获得页面中的样式表
var navName=document.getElementById(‘nav’);
var navList=navName.childNodes;//获得点击对象
window.onload = actFun;
function actFun() {
for(var i=0; i<navList.length; i++){
navList[i].onclick=function(){
tarObj[‘href’]=’css/’+this.className+’.css’
}
}

}

查看DEMO



Leave a Reply

Your email address will not be published. Required fields are marked *

*