(1)功能描述:
点击对应的换肤按钮,实现改变页面整个肤色的功能。(可以配合cookie使用以达到更好效果,这个例子只是简单的实现切换皮肤)
(2)实现代码:
html:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> <link id="changeSkin" rel="stylesheet" href="red.css" /> <!-- 这里的CSS样式为公共样式 --> <style> *{margin: 0px;padding: 0px;} body{font-size: 12px;} li{list-style: none;} #box{width: 500px;margin: 50px auto;} #box #skin{overflow: hidden;} #box #skin li{float: left;width: 6px;height: 6px;border: 4px solid;margin-right: 10px;} #box #skin li.active{background-color: white!important;} #box #skin #red{background-color: red;border-color: red;} #box #skin #green{background-color: green;border-color: green;} #box #skin #black{background-color: black;border-color: black;} #box #nav{overflow: hidden;margin-top: 10px;} #box #nav li{float: left;padding: 5px 25px;border: 1px solid;border-right: none;height: 20px;line-height: 20px;} </style> </head> <body> <div id="box"> <ul id="skin"> <li id="red" class="active"></li> <li id="green"></li> <li id="black"></li> </ul> <ul id="nav"> <li>新闻</li> <li>娱乐</li> <li>体育</li> <li>电影</li> <li>音乐</li> <li style="border-right:1px solid;">旅游</li> </ul> </div> </body> </html>
CSS:(分别保存为单独的.css文件)
red.css
body{background-color: #ffdddd;color: #fff;} #box #nav li{background-color: red;}
green.css
body{background-color: #a3c5a8;color: #fff;} #box #nav li{background-color: green;}
black.css
body{background-color: #ccc;color: #fff;} #box #nav li{background-color: #000;}
js:
<script> window.onload=function(){ var oSkin = document.getElementById("skin"); var aBtn = document.getElementsByTagName("li"); var chaS = document.getElementById("changeSkin"); for(var i=0;i<aBtn.length;i++){ aBtn[i].onclick=function(){ for(var j=0;j<aBtn.length;j++){ aBtn[j].className=""; } this.className="active"; chaS.href=this.id+".css"; } } } </script>
(3)效果图如下所示:
(4)实现原理:
通过点击换肤按钮,获取相应的ID值,从而改变 link 标签的 href 属性达到切换皮肤的功能。