我一直在这里寻找,并找到了在2个css文件之间切换的方法,但不会有更多的文件。我需要使用1个按钮在4个不同的文件之间切换。我用html加载的主css称为style1.css
。
我发现了一个js片段,它可以对图像执行此操作,它所做的是将所有图像放在一个数组中,并从中取出第一个对象并将其放在数组的最后一个对象中。我已经能够做到这一点:
var imageUrls = ["images/paulfr.jpg", "images/johnfr.jpg",
"images/georgefr.jpg", "images/ringofr.jpg"];
function changeImage(){
var img = document.getElementById('image');
var imageUrl = imageUrls.shift();
img.src = imageUrl;
imageUrls.push(imageUrl);
}
现在,我尝试为样式表文件重新制作它,但失败了:
var stylesUrls = ["css/style1.css", "css/style2.css",
"css/style3.css", "css/style4.css"];
function changeStylesheet(){
var style = document.getElementById('styles');
var stylesUrl = stylesUrls.shift();
style.src = stylesUrl;
stylesUrls.push(stylesUrl);
}
我确实确定了样式表id是"styles"。有人能告诉我哪里错了吗?
将src更改为href:
style.src = stylesUrl;
至
style.href = stylesUrl;
完整解决方案:
var stylesUrls = ["css/style1.css", "css/style2.css",
"css/style3.css", "css/style4.css"];
window.onload = function(){
var refButton = document.getElementById("change-styles");
refButton.onclick = function() {
var style = document.getElementById('styles');
var stylesUrl = stylesUrls.shift();
style.href = stylesUrl;
stylesUrls.push(stylesUrl);
}
};
HTML
<link href="css/style1.css" rel="stylesheet" id="styles" type="text/css">
<a href="#" id="change-styles">Change</a>