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 リンクを head に追加する必要があります

             $(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 の実際のスタイルシートが正しくない

于 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 に答える