利用 javascript 来调用css样式

2006-08-10 08:54:13

原文:[url=http://www.alistapart.com/articles/alt&#101;rnate/]Alternative Style: Working With Alternate Style Sheets[/url] 利用javascript控制css来变换自己web的样式 [code]//原文地址:http://www.alistapart.com/articles/alt&#101;rnate/ 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 cr&#101;ateCookie(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(); cr&#101;ateCookie("style", title, 365); } var cookie = readCookie("style"); var title = cookie ? cookie : getPreferredStyleSheet(); setActiveStyleSheet(title); [/code]<!--默认样式--> <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="alt&#101;rnate 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>