javascript調用css

來源:互聯網
上載者:User

//原文地址:[url]http://www.alistapart.com/articles/alternate/[/url]
function setActiveStyleSheet(title) { //根據傳遞的指定 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() { //擷取當前使用樣式的 title
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) { //建立 Cookie
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) { //擷取指定 Cookie
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) {  //視窗載入時,調用 Cookie 記錄的樣式
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); 

 

<!--預設樣式-->
<link title="gr" media="screen" xhref="style.css" type="text/css" rel="stylesheet" />
<!--備用樣式-->
<link title="or" media="screen" xhref="style2.css" type="text/css" rel="alternate stylesheet" />

 

<script xsrc="styleswitcher.js" type="text/javascript"><!--控制預設樣式--><a xhref="#" onclick="setActiveStyleSheet('gr'); return false;">Style1</a>
<!--控製備用樣式--><a xhref="#" onclick="setActiveStyleSheet('or'); return false;">Style2</a>

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.