4

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

3 回答 3

3

所以,正如一些评论所说,你最好的选择是切换 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>
于 2012-09-06T15:25:32.823 回答
1

css链接必须添加到头部

             $(document).ready(function() {
               //load silver automatically in ready

                 $("a.silver").click(function() {
                         $('head > link').last().remove();   //removes red and adds silver
                         $('head').append('<link rel="stylesheet" href="style2.css" type="text/css" />');
                   });

                 $("a.red").click(function() {
                        $('head > link').last().remove();  //remove silver - adds red
                        .append('<link rel="stylesheet" type="text/css" href="themes/silver/css/template.css"/>');
                          });
                    });
             });

the actual stylesheets in my jQuery aren't correct

于 2012-09-06T15:02:46.840 回答
1

如前所述,切换 css 样式而不是文件可能是最佳实践,但如果需要切换文件,请尝试:

$(function(){
    $('a.silver').click(function (){
       $('link[href="css/template.css"]').attr('href','themes/silver/css/template.css');
    });
    $('a.red').click(function (){
       $('link[href="themes/silver/css/template.css"]').attr('href','css/template.css');
    });
});

在此解决方案中,您还必须像往常一样在头部定义样式...

于 2012-09-06T15:08:37.563 回答