2016-09-08 205 views
0

如何將其變成切換按鈕?所以當按鈕被點擊時,它會切換明暗背景。用開關切換背景圖像(jQuery)

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

CSS

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

感謝

+1

撥動一類... – epascarello

回答

5

切換的一類,而不是直接設置背景。這將是更容易維護,並知道代碼處於什麼狀態。

$(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>

+0

1秒Outdrawn。帶上你的讚賞:) –