方法比较多,感觉这种比较好。效果可以看老鬼的日志网站。 代码分成三部分。 连接 CSS 样式: HTML: <!-- 默认样式 --> <link rel="stylesheet" type="text/css" media="screen" href="css/default.css" /> <!-- 备选样式 --> <link rel="alternate stylesheet" type="text/css" media="screen" href="css/green.css" title="green" /> <link rel="alternate stylesheet" type="text/css" media="screen" href="css/red.css" title="red" /> 假设有一个默认样式,还有绿色和红色两种可供选择的样式。 JavaScript 脚本: PHP: // ---------------------------------------------- // StyleSwitcher functions written by Paul Sowden // http://www.idontsmoke.co.uk/ss/ // - - - - - - - - - - - - - - - - - - - - - - - // For the details, visit ALA: // http://www.alistapart.com/stories/alternate/ 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); 使用部分: HTML: <ul> <li><a href="javascript: void(0)" onclick="setActiveStyleSheet('', 1); return false;">默认</a></li> <li><a href="javascript: void(0)" onclick="setActiveStyleSheet('green', 1); return false;">绿色</a></li> <li><a href="javascript: void(0)" onclick="setActiveStyleSheet('red', 1); return false;">红色</a></li> </ul> 调用 setActiveStyleSheet 函数,运用指定样式。