javascript - 如何使用 jQuery 切换样式表?

标签 javascript jquery html css

我设计了一个多色模板,现在我只想在单击颜色图标时更改“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/

相关文章:

javascript - 如何加载麦克风请求并使其保持事件状态

javascript - 如何在不提交表单的情况下获取 javascript 中输入字段的值?

php - 使用 jQuery 的日期选择器

javascript - 更改 URL 的默认颜色代码

javascript - javaScript 中的内存泄漏?

javascript - 本地下载的文件已损坏

javascript - jQuery 快速过滤问题与搜索范围标题属性

javascript - 如何更改按类迭代的id值

javascript - 传单标记图标点击事件不起作用

javascript - 添加迄今为止的天数