したがって、いくつかのコメントが言ったように、最善の策は 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>