2015-10-22 54 views
0

我需要在jquery中找到正確的代碼,這將允許我通過按鈕快速切換樣式表。我目前沒有jQuery,因爲我的所有失敗。我仍然在學習它。總之,這裏是HTML:使用jquery切換樣式表

/* Theme 1 */ 
 
body { 
 
\t background: #ff4455; 
 
} 
 
/* Theme 2 */ 
 
body { 
 
\t background: #ee7744; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
 
<body> 
 
\t <input type="button" id="theme1"> 
 
\t <input type="button" id="theme2"> 
 

 
\t <script type="text/javascript"></script> 
 
</body>

下面是代碼片段。我需要的內部jQuery的<script type="text/javascript"></script>

感謝您的幫助! :D

回答

0

嘗試使用style元素與type設置爲text/plain;點擊input type="button"設置style type="text/css"style type="text/plain"的文字內容classid相同input type="button"點擊。方法能保持相同的文檔中的所有css,而不需要在款式

$("input[type=button]").click(function() { 
 
    $("[type$=css]").text($("." + this.id).text()) 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<style type="text/css"> 
 
</style> 
 
<style type="text/plain" class="theme1"> 
 
    /* Theme 1 */ 
 
    body { background: #ff4455; } 
 
</style> 
 
<style type="text/plain" class="theme2"> 
 
    /* Theme 2 */ 
 
    body { background: #ee7744; } 
 
</style> 
 

 
<body> 
 
    <input type="button" id="theme1" value="theme1"> 
 
    <input type="button" id="theme2" value="theme2"> 
 
</body>

+0

每個切換請求外部樣式表同樣的偉大工程,謝謝! :d – Akados

0

應該有很多類似的問題和答案,無論如何這裏有一個。

<html> 
<head> 
    <link href="css/sheet1.css" rel="stylesheet" type="text/css" id="sheet1"> 
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 
</head> 
<body> 
    <input type="button" id="theme1"> 
    <input type="button" id="theme2"> 
    <script type="text/javascript"> 
    $(document).ready(function() { 
     $('#theme1').click(function(){ 
      $('#sheet2').remove(); 
      $('head').append('<link href="css/sheet1.css" rel="stylesheet" id="sheet1" />'); 
     }); 
     $('#theme2').click(function(){ 
      $('#sheet1').remove(); 
      $('head').append('<link href="css/sheet1.css" rel="stylesheet" id="sheet2" />'); 
     }); 
    }); 
    </script> 
</body> 
</html> 
0

在你<head>部分,把這樣的事情:

<link rel="stylesheet" id="currentStyle" href="theme1.css"> 

然後在你的代碼塊,做這樣的事情:

$(function() 
{ 
     $("button").click(function() 
      { 
       $("#currentStyle").attr("href", $(this).attr("id") + ".css"); 
      }); 
}); 

它將掛鉤的函數是隻要點擊一個按鈕就可以調用該頁面的樣式表作爲附加了「.css」的按鈕的ID值。因此,如果單擊了id =「theme1」的按鈕,則爲「theme1.css」。