Toggle between two stylesheets

后端 未结 7 1655
北荒
北荒 2020-12-11 03:38

I am trying to add in a very simple method of switching between 2 stylesheets.

I can get the stylesheet to fire on click but not able to toggle it back to its origin

相关标签:
7条回答
  • 2020-12-11 03:40

    You can use detach using jquery

    <script>
        (function() {
          var styles = {
            light: $("#light").detach(),
            dark:  $("#dark")
          };
    
          $("input[name=chooseStyle]").click(function() {
            var other = this.value === "light" ? "dark" : "light";
            styles[this.value].appendTo('head');
            styles[other].detach();
          });
        })();
      </script>

    Demo link

    0 讨论(0)
  • 2020-12-11 03:41

    Instead of long href use link[href*="style.css"] to find style.css

    var click = false;
    var path = '/rip-access/wp-content/themes/RIP/assets/css/';
    
    $('#css_toggle').on('click', function() {
      if (!click) {
        $('link[href*="style.css"]').attr('href', path + 'style1.css');
        click = true;
        console.log('changed to style1.css');
      } else {
        $('link[href*="style1.css"]').attr('href', path + 'style.css');
        click = false;
        console.log('changed to style.css');
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <button id="css_toggle" title="I'm a tooltip!">Toggle</button>
    <link href="/rip-access/wp-content/themes/RIP/assets/css/style.css" rel="stylesheet" />

    And also you could use an ID instead of selecting by file name.

    $('#css') // jquery selector
    
    <link id="css" href="..." rel="stylesheet" /> // html
    
    0 讨论(0)
  • 2020-12-11 03:52

    Not as elegant as some previous answers, but hopefully easy to follow for relative beginners like me:

    In summary, this code produces a button that switches between two stylesheets (light.css and dark.css), and also updates the text on the button.

    (1) In your HTML, give the stylesheet link an id (style), and set up an empty div (button-container), which will contain the button:

    <head>
    <link id="style" rel="stylesheet" href="light.css" />
    </head>
    
    <body> 
    <div class="button-container"></div>
    </body>
    

    (2) In your script block or script.js file, store the current href value of the stylesheet link in a variable (theme):

    let theme = $("head link#style").attr("href");
    

    (3) Insert a button into your button-container div. The button has an onclick handler, which calls a function called toggleTheme:

    $(".button-container").html('<button id="theme" onclick="toggleTheme()">dark mode</button>');
    

    (4) the toggleTheme function checks the current value of the variable theme, assigns it the value of the other stylesheet, and updates the button text:

    function toggleTheme() {
        if (theme == "light.css") {
            theme = "dark.css";
            $("head link#style").attr("href", theme);
            $(".theme").html(
                '<button id="theme" onclick="toggleTheme()">light mode</button>'
            );
        } else {
            theme = "light.css";
            $("head link#style").attr("href", theme);
            $(".theme").html(
                ' <button id="theme" onclick="toggleTheme()">dark mode</button>'
            );
        }
    }
    
    0 讨论(0)
  • 2020-12-11 03:54

    This is an alternative solution to consider if, for some reason, Rory's solution cannot be applied. It's ideal to simply toggle a body class and use this class as a base selector - I've recently applied this method for an application switching between a dark and light theme, then storing it to localStorage so that the changes are "remembered" e.g:

    <style>
        .nocturnal-theme p {
           background: black;
           color: white;
        }
    
        .diurnal-theme p {
           background: white;
           color: black;
        }
    </style>
    
    <script>
    /* Toggle Theme */
    jQuery('.toggle-theme').on('click', function(){
        if(jQuery(this).hasClass('toggle-diurnal')) {
            jQuery('body').removeClass('diurnal-theme').addClass('nocturnal-theme');
            localStorage.setItem('theme','nocturnal-theme');
        } else if(jQuery(this).hasClass('toggle-nocturnal')) {
            jQuery('body').removeClass('nocturnal-theme').addClass('diurnal-theme');
            localStorage.setItem('theme','diurnal-theme');
        }
        var themeSet = localStorage.getItem('theme');
    });
    </script>
    

    Summary

    1. The below solution stores the relative filepaths (typical of standard Wordpress installations) to variables (you may not always have unique identifiers (id attribute values) available to use, and since editing core files, to include one, is not considered good practice (for reasons that won't be touched on here) it may be better to store these filepaths in variables);
    2. On .click() of '#css_toggle', the .each() method is used to loop through all instances of stylesheets (of which there would most likely be a few), it also allows us to redefine the scope of $(this) which will prove helpful moving forward;
    3. Through each iteration of the loop, the link currently in scope has its href attribute stored in a variable;
    4. The stored value of this attribute is then compared with the relative filepaths we stored in variables previously
    5. If they are found to contain these stored values, the href attribute of the link element in question is updated accordingly

    Code Snippet Demonstration:

    var defaultSS = '/wp-content/themes/RIP/assets/css/style.css',
        altSS = '/wp-content/themes/RIP/assets/css/style1.css',
        hrefAttr;
    
    $('#css_toggle').click(function () {
    
      $('link').each(function(){
        hrefAttr = $(this).attr('href');
        if (hrefAttr.indexOf(defaultSS) >= 0) {
          $(this).attr('href', altSS);
          
          console.log('Was:',hrefAttr);
          console.log('Now:',$(this).attr('href'));
          
        } else if (hrefAttr.indexOf(altSS) >= 0) {
          $(this).attr('href', defaultSS);
          
          console.log('Was:',hrefAttr);
          console.log('Now:',$(this).attr('href'));
          
        }
      });
    
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link rel="stylesheet" href="http://localhost:8888/rip-access/wp-content/themes/RIP/assets/css/style.css" type="text/css" media="all">
    
    <button id="css_toggle" title="I'm a tooltip!">Text</button>

    0 讨论(0)
  • 2020-12-11 03:58

    A better, and more reliable, solution would be to use a single stylesheet and alternate the styling by making the rules depend on a class on the body. You can then just toggle that class when needed, something like this:

    $('#css_toggle').click(function() {
      $('body').toggleClass('default highlight');
    });
    body.default .sq {
      border: 1px solid #C00;
    }   
    
    body.highlight .sq {
      background-color: #CC0;
      border: 2px dotted #C00;
    }
    
    .sq {
      margin: 10px 0 0;
    }
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <body class="default">
      <button id="css_toggle" title="I'm a tooltip!">Text</button>
      <div class="sq">
        Foo
      </div>
    </body>

    0 讨论(0)
  • 2020-12-11 03:58

    You can try something like this :

    let test = true;
    $('#css_toggle').click(function() {
      if(test) {
        $('link.sty').attr("href","style.css");
        test = false;
      } else {
        $('link.sty').attr("href","style1.css");
        test = true;
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <link class="sty" href="style.css" rel="stylesheet">
    
    <button id="css_toggle" title="I'm a tooltip!">Text</button>
    <div class="sq"></div>

    0 讨论(0)
提交回复
热议问题