您的位置:首页 > Web前端 > HTML5

<HTML5程序开发范例宝典(韩旭著)>读书笔记之页面风格切换实例

2016-10-27 00:00 211 查看
摘要: 具体代码解析请见该书1.1中的实例002网页换肤

这个demo是可运行的,html和css都比较简单,主要是js部分会稍微复杂一点。
另外一定要确保引入的路径没有问题,比如我的文件是这样放的:



html:

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<link id="myCss" rel="stylesheet" href="css/style1.css">
</head>
<body leftmargin="0" topmargin="0" onLoad="ifCookie();">
<div id="wrap">
<div class="nav">
<a href="#" onClick="change('myCss','css/style1.css')">样式一</a>
<a href="#" onClick="change('myCss','css/style2.css')">样式二</a>
</div>
<div><button class="testBtn">测试按钮</button></div>
</div>
<script>
function writeCookie(cssPath){
//设置cookie的值为30天
var today=new Date();
var expires=new Date();
expires.setTime(today.getTime()+1000*60*60*24*30);//有效期为30天
var str="cssPath="+cssPath+";expires="+expires.toGMTString()+";";
document.cookie=str;
}
function readCookie(cookieName){
var search=cookieName+"=";
if(document.cookie.length>0){
offset=document.cookie.indexOf(search);
if(offset != -1){
offset+=search.length;
end=document.cookie.indexOf(";",offset);
if(end==-1){
end=document.cookie.length;
return unescape(document.cookie.substring(offset,end));
}
}
}
}
//ifCookie(),初始化页面风格
function ifCookie(){
if(readCookie("cssPath")==undefined){//当标记网页style的cookie不存在
writeCookie("css/style1.css");
}
document.getElementById("myCss").href=readCookie("cssPath");
}
//change(),用于改变页面的整体风格
function change(myCss,cssPath){
writeCookie(cssPath);
document.getElementById(myCss).href=readCookie("cssPath");
}
</script>
</body>
</html>

style1.css

*{
margin:0;
padding:0;
box-sizing:border-box;
}
body
{
background-color:#fff;
font-size:18px;
font-family:"Arial","Tahoma","微软雅黑","雅黑";
line-height:18px;
padding:0px;
margin:0px;
text-align:center;
}
button
{
font-family:"Arial","Tahoma","微软雅黑","雅黑";
border:0px;
vertical-align:middle;
margin:8px;
line-height:18px;
font-size:18px;
}
.testBtn{
width:145px;
height:34px;
line-height:22px;
font-size:22px;
color:#959595;
padding-bottom:4px;
}

style2.css:

*{
margin:0;
padding:0;
box-sizing:border-box;
}
body
{
background-color:#fff;
font-size:18px;
font-family:"Arial","Tahoma","微软雅黑","雅黑";
line-height:18px;
padding:0px;
margin:0px;
text-align:center;
}
button
{
font-family:"Arial","Tahoma","微软雅黑","雅黑";
border:0px;
vertical-align:middle;
margin:8px;
line-height:18px;
font-size:18px;
}
.testBtn{
width:144px;
height:42px;
line-height:18px;
font-size:18px;
color:#ff6000;
padding-bottom:4px;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  页面换肤