无刷新cookies切换样式示例代码实例主要用到的代码
复制代码 代码如下:
<html>
<head>
<metahttp-equiv="Content-Type"content="text/html;charset=gb2312">
<title>styleswitcher查字典教程网-www.jb51.net</title>
<linktitle=redrel="stylesheet"type="text/css"href="red.css">
<LINKtitle=bluehref="blue.css"type=text/cssrel="alternatestylesheet">
<SCRIPTsrc="styleswitcher.js"type=text/javascript></SCRIPT>
<style>
<>
</style>
</head>
<body>
<Aonclick="setActiveStyleSheet('red');returnfalse;"href="#">red</A>
<Aonclick="setActiveStyleSheet('blue');returnfalse;"href="#">blue</A>
<selectname="changestyle"size="1">
<optionvalue="red">red</option>
<optionvalue="blue">blue</option>
</select><inputtype="button"value="变"onclick="setActiveStyleSheet(changestyle.value);returnfalse;">
<divid="wrapper">
<divid="left">left</div>
<divid="right">right</div>
</div>
</body>
</html>
styleswitcher.js
复制代码 代码如下:
//styleswitcher.js
functionsetActiveStyleSheet(title)
{
vari,a,main;
for(i=0;(a=document.getElementsByTagName("link")[i]);i++)
{
if(a.getAttribute("rel").indexOf("style")!=-1&&
a.getAttribute("title"))
{
a.disabled=true;
if(a.getAttribute("title")==title)
a.disabled=false;
}
}
}
functiongetActiveStyleSheet()
{
vari,a;
for(i=0;(a=document.getElementsByTagName("link")[i]);i++)
{
if(a.getAttribute("rel").indexOf("style")!=-1&&
a.getAttribute("title")&&!a.disabled)
returna.getAttribute("title");
}
returnnull;
}
functiongetPreferredStyleSheet()
{
vari,a;
for(i=0;(a=document.getElementsByTagName("link")[i]);i++)
{
if(a.getAttribute("rel").indexOf("style")!=-1&&
a.getAttribute("rel").indexOf("alt")==-1&&
a.getAttribute("title"))
returna.getAttribute("title");
}
returnnull;
}
functioncreateCookie(name,value,days)
{
if(days)
{
vardate=newDate();
date.setTime(date.getTime()+(days*24*60*60*1000));
varexpires=";expires="+date.toGMTString();
}
elseexpires="";
document.cookie=name+"="+value+expires+";path=/";
}
functionreadCookie(name)
{
varnameEQ=name+"=";
varca=document.cookie.split(';');
for(vari=0;i<ca.length;i++)
{
varc=ca[i];
while(c.charAt(0)=='')
c=c.substring(1,c.length);
if(c.indexOf(nameEQ)==0)
returnc.substring(nameEQ.length,c.length);
}
returnnull;
}
window.onload=function(e)
{
varcookie=readCookie("style");
vartitle=cookie?cookie:getPreferredStyleSheet();
setActiveStyleSheet(title);
}
window.onunload=function(e)
{
vartitle=getActiveStyleSheet();
createCookie("style",title,365);
}
varcookie=readCookie("style");
vartitle=cookie?cookie:getPreferredStyleSheet();
setActiveStyleSheet(title);
red.css
复制代码 代码如下:
#left{background-color:#0000FF;float:right;}
red.css
复制代码 代码如下:
#left{background-color:#FF0000;float:left;}