Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

jquery - Toggle between two stylesheets

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 original:

<button id="css_toggle" title="I'm a tooltip!">Text</button>
<div class="sq"></div>  
$('#css_toggle').click(function () {
  $('link[href="http://localhost:8888/rip-access/wp-content/themes/RIP/assets/css/style.css"]').attr('href', 'http://localhost:8888/rip-access/wp-content/themes/RIP/assets/css/style1.css').toggle();
});

this is a VERY simple example so I can understand how to do it before I continue on. Any ideas how I can get it toggle back to the first stylesheet?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...