2014-01-08 28 views
0

我必須忽視的東西,但下面的代碼是不是爲我工作的值的變量(對不起,這麼基本的東西):分配到的樣式屬性不工作

(function(){ 
    document.body.addEventListener("click", function(){ 
     var test = "rgb(" + parseInt((9.3 * Math.random())) + "," + parseInt((9.1 * Math.random())) + "," + parseInt((102 * Math.random())) + ");"; 
     this.style.backgroundColor = test; 
     console.log(test); // corretly outputs rgb(12, 20, 30) 
    }, false); 
})(); 

使用字符串值工作並將變量分配給包含rgb值的字符串也可以,但使用test作爲該值不起作用,並且不顯示任何控制檯錯誤。爲什麼是這樣?

+0

您可以張貼演示,重現該問題? – elclanrs

回答

2

刪除;它不正確輸出rgb(12, 20, 30),它輸出rgb(12, 20, 30);

你正在設定

this.style.backgroundColor = "rgb(12, 20, 30);"; 

存在導致該值無效的分號。你需要從字符串

+ ");"; 
    ^

分號去掉它應該是

+ ")"; 
+0

完美,謝謝! – user2129623

2

你不需要在年底通過;

var test = 
    "rgb(" 
    + parseInt((9.3 * Math.random())) 
    + "," 
    + parseInt((9.1 * Math.random())) 
    + "," 
    + parseInt((102 * Math.random())) + ")"; 

+ ");"

DEMO

0

而且你的色彩範圍不夠大才能注意到差別,12,30和7將類似於。試試這個:

(function() { 
    document.addEventListener('click', function() { 
     var r = Math.round(Math.random() * 255), 
      g = Math.round(Math.random() * 255), 
      b = Math.round(Math.random() * 255); 
     document.body.style.backgroundColor = 'rgb(' + r + ', ' + g + ', ' + b + ')'; 
    }); 
})(); 

這裏是工作提琴:

http://jsfiddle.net/kmturley/7zNv6/