将 document.body.style.backgroundColor 分配给变量

Assign document.body.style.backgroundColor to a variable

我正在制作一个简单的颜色转换器。 我将 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)];