My studying notebook

2008/06/03

Css-Switcher

6/03/2008 09:46:00 PM Posted by Unknown , , 1 comment
利用Css可以快速改變HTML的風格樣式。在網頁中載入Css的方法則可以使用3種


<link rel="stylesheet" href="css/Clean.css" type="text/css">
<!--Method2: Embed Style-->
<style type="text/css">/*Css Code*/</style>
<!--Method3: Inline Sytle-->
<p style="color: red;">this is paragraph</p>


除了使用設計好的Css樣式之外,Javascript還可以讓我們動態的改變目前網頁中使用的樣式

<link rel="stylesheet" href="css/Clean.css" type="text/css">
<link rel="alternate stylesheet" href="css/Digg.css" type="text/css" title="Digg">
<link rel="alternate stylesheet" href="css/Flickr.css" type="text/css" title="Flickr">

Clean.css為預設網頁使用樣式,Digg.css & Flickr.css則為Javascript動態載入之樣式

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 < c =" ca[i];" c =" c.substring(1,c.length);" onload =" function(e)" cookie =" readCookie(" title =" cookie" onunload =" function(e)" title =" getActiveStyleSheet();" cookie =" readCookie(" title =" cookie">

在頁面中簡單的使用Hyperlink,將Css link中Title的參數指向Javascript中的setActiveStyleSheet Function

<a href="#" onclick="setActiveStyleSheet(''); return false;">預設載入的樣式</a>
<a href="#" onclick="setActiveStyleSheet('Digg'); return false;">動態載入Digg樣式</a>
<a href="#" onclick="setActiveStyleSheet('Flickr'); return false;">動態載入Flickr樣式</a>


Live Demo

1 comment: