2017-01-06 117 views
2

單擊按鈕div時,我想將主體更改爲「顏色」數組中的隨機顏色。此代碼有效,但僅在第一次點擊時才起作用。我可以改變身體每次點擊div時改變顏色?每次單擊div時更改主體背景顏色

var colors = ["#3b609b", "#9b3b3b", "#3b9b81", "#7da5a4"]; 
var rand = Math.floor(Math.random() * colors.length); 

$(".button").click(function() { 
    $("body").css("background-color", colors[rand]); 
}) 
+5

,就把這行'VAR蘭特= Math.floor(的Math.random()* colors.length);'在點擊功能;) – d3vi4nt

+1

你設置'rand'只有一次,但你想每次點擊'div'設置它 – d3vi4nt

+0

@ d3vi4nt哇,不能相信我錯過了,謝謝它的工作! – Zach

回答

6

在你的代碼,rand變量的值保持相同的每次點擊。

您需要在每次點擊時更新此值,以便將此行代碼var rand = Math.floor(Math.random() * colors.length)放置在點擊處理程序中。

var colors = ["#3b609b", "#9b3b3b", "#3b9b81", "#7da5a4"]; 
 

 

 
$(".button").click(function() { 
 
    var rand = Math.floor(Math.random() * colors.length); 
 
    $("body").css("background-color", colors[rand]); 
 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<h1>Gaurav</h1> 
 
<button class="button"> Change Color</button>

+0

謝謝,它的工作! – Zach

+0

@Zach快樂編碼 –