變換網頁樣式呈現不同風格(cookie):變更頁面所要引入的css檔,可應用在版面風格、顏色版面設計

head
-----------------------------
<link rel="stylesheet" type="text/css" href="style.css" title="default">
<link rel="stylesheet" type="text/css" href="style1.css" title="style_one">
<link rel="stylesheet" type="text/css" href="style2.css" title="style_two">
<script type="text/javascript" src="styleswitcher.js"></script>


body
----------------------------
<a href="#" onclick="setActiveStyleSheet('default'); return false;">default</a>
<a href="#" onclick="setActiveStyleSheet('style_one'); return false;">style_one</a>
<a href="#" onclick="setActiveStyleSheet('style_two'); return false;">style_two</a>


參考網址:
http://www.hsiu28.net/style/article_detail.php?id=12

js 位置:
http://www.hsiu28.net/style/html/styleswitcher.js



// JavaScript template using Windows Script Host
function setActiveStyleSheet(title) {
var i, 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;
}
}
}

function getActiveStyleSheet() {
var i, a;
for(i=0; (a = document.getElementsByTagName("link")[i]); i++) {
if(a.getAttribute("rel").indexOf("style") != -1 && a.getAttribute("title") && !a.disabled) return a.getAttribute("title");
}
return null;
}

function getPreferredStyleSheet() {
var i, 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")
) return a.getAttribute("title");
}
return null;
}

function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}

window.onload = function(e) {
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
}

window.onunload = function(e) {
var title = getActiveStyleSheet();
createCookie("style", title, 365);
}

var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
創作者介紹
創作者 Rita 的頭像
Rita

Watermeloner

Rita 發表在 痞客邦 留言(0) 人氣()