admin管理员组

文章数量:1326320

How do i turn this into a toggle button? So that when the button is clicked, it toggles the light and dark background.

$(document).ready(function(){
   $("button").click(function(){
       $(".content1").css("background-image", "url(../images/light.png)");  
   });
});

CSS

.content1 {
background-image: url('../images/dark.png');
}

Thanks

How do i turn this into a toggle button? So that when the button is clicked, it toggles the light and dark background.

$(document).ready(function(){
   $("button").click(function(){
       $(".content1").css("background-image", "url(../images/light.png)");  
   });
});

CSS

.content1 {
background-image: url('../images/dark.png');
}

Thanks

Share Improve this question edited Sep 8, 2016 at 14:25 bipen 36.6k9 gold badges50 silver badges62 bronze badges asked Sep 8, 2016 at 14:23 user5635857user5635857 1
  • 2 toggle a class... – epascarello Commented Sep 8, 2016 at 14:23
Add a ment  | 

1 Answer 1

Reset to default 7

Toggle a class instead of setting the background directly. It will be easier to maintain and to know what state the code is in.

$(document).ready(function() {
  $("button").click(function() {
    $(".content1").toggleClass("active");
  });
});
.content1 {
  background-image: url('../images/dark.png');
  background-color: red;
}
.content1.active {
  background-image: url('../images/light.png');
  background-color: green;
}
<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button>Clicky</button>
<div class="content1"> Hello </div>

本文标签: javascriptChange background image with a toggle (jQuery)Stack Overflow