我正在做一個簡單的換色器。
我把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)
})
uj5u.com熱心網友回復:
通過這樣做,你只是復制(保存)了document.body.style.backgroundColor的字面值,而不是一個指向該的東西。所以給變數分配一個新值并不影響document.body.style.backgroundColor。
你只是再次改變了值:
backgroundColor = colors[Math. floor(Math.random() * colors.length) ] 。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/316185.html
標籤:
