我有一个带有 javascript 的样式表更改器,但它在 IE 中不起作用,而在 Firefox 和 Chrome 中运行良好。我正在使用的 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");
}
}
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");
}
}
function getTheme() {
var storedThemeVal = readCookie('selectedTheme');
if (storedThemeVal != null && storedThemeVal != "") {
for (var i = 0; i < selectBox.options.length; i++) {
if (selectBox.options[i].value == storedThemeVal) {
selectBox.selectedIndex = i;
}
}
}
}
function setTheme() {
var selectedThemeVal = selectBox.options[selectBox.selectedIndex].value;
createCookie('selectedTheme', selectedThemeVal);
}
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;
}
function initiate()
{
window.selectBox = document.getElementById("myList");
var cookie = readCookie("style");
var title = cookie ? cookie : getPreferredStyleSheet();
setActiveStyleSheet(title);
getTheme();
selectBox.onchange = function () {
setActiveStyleSheet(this.value);
setTheme();
};
}
window.onload = initiate;
我不明白为什么这在 IE 中不起作用,因为它在其他浏览器中运行良好。而且我更喜欢将我所有的 javascript 保存在我的单独文档 javascript.js 中,并且我不想使用库。