简体   繁体   English

使用切换按钮更改背景图片(jQuery)

[英]Change background image with a toggle (jQuery)

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 的CSS

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

Thanks 谢谢

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.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <button>Clicky</button> <div class="content1"> Hello </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM