所以,正如一些评论所说,你最好的选择是切换 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>