繁体   English   中英

如何使用jQuery切换样式表?

[英]How do I switch stylesheets with jQuery?

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

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"/>');
                          });
                    });
             });

我的jQuery中的实际样式表不正确

如前所述,最好的方法是切换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');
    });
});

在此解决方案中,您还必须像通常那样在头中定义样式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM