讀書筆記之頁面風格切換實例

這個demo是可運行的,html和css都比較簡單,主要是js部分會稍微複雜一點。 另一定要確保引入的路徑沒有問題,好比個人文件是這樣放的: css

html: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.csscookie

*{
	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;
}
相關文章
相關標籤/搜索