我设计了一个多色模板,现在我只想在单击颜色图标时更改“CSS”文件,请问有人可以帮我吗?
这是我的代码,但效果不佳,只能更改一次颜色。
$(document).ready(function() {
$("a.silver").click(function() {
$("a.silver").append('<link rel="stylesheet" type="text/css" href="themes/silver/css/template.css"/>');
});
$("a.red").click(function() {
$("a.red").append('<link rel="stylesheet" type="text/css" href="css/template.css"/>');
});
});
最佳答案
因此,正如一些评论所说,最好的办法是切换 CSS 类。但是,如果您要更改整个页面样式,那么交换样式表对我来说似乎是个好主意。但是您不必在每次要交换样式表时都“重新生成”元素。您最好只在必要时将它们从 DOM 中分离出来。所以像这样:
$(document).ready(function() {
var sheets = { //a map of sheets. Simply add sheets to this to add more themes (and create appropriate links to them)
silver: $('<link rel="stylesheet" type="text/css" href="themes/silver/css/template.css"/>'),
red: $('<link rel="stylesheet" type="text/css" href="css/template.css"/>')
};
var currentSheet = sheets.red.appendTo($("head")); //attach default sheet
$("a.swapStyle").click(function () {
currentSheet.detach(); //remove the current sheet
currentSheet = (sheets[$(this).attr("data-theme")]).appendTo($("head")); //attach a new sheet and set the currentSheet variable to remember it.
});
});
您需要将链接更改为如下内容:
<a href="javascript:void(0)" class="swapStyle" data-theme="red">Change to red theme</a>
<a href="javascript:void(0)" class="swapStyle" data-theme="silver">Change to silver theme</a>
关于javascript - 如何使用 jQuery 切换样式表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12302872/