另一件事是 document.write 并不是很好的做法.在这种情况下,很容易避免这种情况,请使用 appendChild : var box = document.getElementById('changeBox');var randR = Math.floor(Math.random()* 255)+ 1;var randG = Math.floor(Math.random()* 255)+ 1;var randB = Math.floor(Math.random()* 255)+ 1;box.appendChild(document.createTextNode(randR +," + randG +," + randB));box.style.backgroundColor ="rgb(" + randR +," + randG +," + randB +)"; 演示: http://jsfiddle.net/zc16vmjt/1/ I am trying to set the div 'changebox' with the color of the rgb which is the result of the three randoms. The rgbs are changing, (i can tell by the document.writes), but the div just stays white no matter what the rgb is. Please help get the box to change to the correct color of the rgb.<div id="changeBox" style="width: 150px; height: 150px; position: absolute; top: 10%; left: 10%; background-color: white; border: 4px solid black; color: black; font-family: 'Merriweather Sans', sans-serif;"><script>var randR = Math.floor(Math.random() * 255) + 1;document.write(randR+", ");var randG = Math.floor(Math.random() * 255) + 1;document.write(randG+", ");var randB = Math.floor(Math.random() * 255) + 1;document.write(randB);document.getElementById('changeBox').style = "background-color: rgb(" + randR + ", " + randG + ", " + randB + ");";</script></div> 解决方案 You should change only background-color property: document.getElementById('changeBox').style.backgroundColor = "rgb(" + randR + ", " + randG + ", " + randB + ")";In this case remove tailing ; to make value valid.Demo: http://jsfiddle.net/zc16vmjt/Another thing is that document.write is not very good practice. It's easy to avoid it in this case and go with appendChild:var box = document.getElementById('changeBox');var randR = Math.floor(Math.random() * 255) + 1;var randG = Math.floor(Math.random() * 255) + 1;var randB = Math.floor(Math.random() * 255) + 1;box.appendChild(document.createTextNode(randR + ", " + randG + ", " + randB));box.style.backgroundColor = "rgb(" + randR + ", " + randG + ", " + randB + ")";Demo: http://jsfiddle.net/zc16vmjt/1/ 这篇关于使用javascript变量更改CSS背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
07-18 12:00
查看更多