如何在jquery/javascript中用一个按钮在两个样式表之间交换



我有一个按钮可以在"浅色主题"和"深色主题"之间切换,但我只更改了一次,没有再次更改。我真的很感激任何帮助!

<link id="sheet" href="main.css" rel="stylesheet">

/

$(".themebutton").click(function() {
if($('a[href="main.css"]'))
{
  $("#sheet").attr('href','dark.css');
}
else {
  $("#sheet").attr('href','main.css');
}
});

还有没有一种方法可以阻止样式表加载时发生的"闪烁"?

实现这一点的最佳方法是为html标记创建类名。想象一下这两个类:

 .theme1 { 
    background:red;
 }
 .theme1 h1 {
     color: blue;
 }
 .theme2 {
    background: green;
 }
 .theme2 h1 {
     color: orange;
 }

您可以在没有闪烁和新请求的情况下切换到服务器,如下所示:

 $('.change-theme-1').on('click', function() {
      $('html').addClass('theme1');
 }

这里有一个片段可以看到它的工作。

$('.change-theme').on('click', function(e) {
  e.preventDefault();
  $('html').addClass('theme'+$(this).attr('rel'));
});
.theme1 { 
  background:red;
}
.theme1 h1 {
  color: blue;
}
.theme2 {
  background: green;
}
.theme2 h1 {
  color: orange;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
  <body>
    <h1>That's a header</h1>
    <button class="change-theme" rel="1">Theme 1</button><br>
    <button class="change-theme" rel="2">Theme 2</button>

最新更新