我正在使用这个 HTML 代码:
<head>
<link href="defualt.css" rel="stylesheet" type="text/css" />
<link href="theme1.css" title="theme1" rel="alternate stylesheet" type="text/css" />
<link href="theme2.css" title="theme2" rel="alternate stylesheet" type="text/css" />
<link href="theme3.css" title="theme3" rel="alternate stylesheet" type="text/css" />
<script type="text/javascript" src="javascript.js"></script>
</head>
<body>
<form>
<select id="myList" >
<option value="default">Default</option>
<option value="theme1">Theme 1</option>
<option value="theme2">Theme 2</option>
<option value="theme3">Theme 3</option>
</select>
</form>
</body>
这是更改样式表的一种形式。这是我正在使用的 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;
}
}
createCookie("style", title, 7);
}
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);
}
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
function initate()
{
document.getElementById("myList").onchange = function() {
setActiveStyleSheet(this.value);
return false
};
}
window.onload = initate;
样式表的更改效果很好,但我希望在重新加载页面后保留菜单中选择的选项。这在 Firefox 中可以正常工作,但在 Chrome 中却不行。我对 javascripts 很陌生,而且我自己还没有编写所有这些代码,所以我并不完全理解所有这些代码。是否可以将所选的菜单选项保存在同一个 cookie 中,还是创建一个新的更好/更容易?