我正在做一个简单的颜色改变器。我把document.body.style.backgroundColor
赋给了有价值的backgroundColor
。当我console.log(backgroundColor)
,我可以看到它的工作,但背景颜色没有改变。所以我只是删除了变量backgroundColor
,并把document.body.style.backgroundColor = colors[Math.floor(Math.random() * colors.length)];
,然后它的工作!但我不能理解为什么它不工作,当我分配document.body.style.backgroundColor
变量如下面的代码。
const btn = document.querySelector('.btn');
const color = document.querySelector('.color');
const colors = ["green", "red", "rgba(133,122,200)", "#f15025"];
btn.addEventListener('click', function() {
let backgroundColor = document.body.style.backgroundColor ;
backgroundColor = colors[Math.floor(Math.random() * colors.length)];
console.log(backgroundColor)
})
通过这样做,您只是复制(保存)document.body.style.backgroundColor
的文字值,而不是指向它的东西。所以给变量赋一个新值不会影响document.body.style.backgroundColor
.
你只是再次改变了值:
backgroundColor = colors[Math.floor(Math.random() * colors.length)];