问题描述
我希望每次单击按钮时都会在生成的十六进制代码旁边更新我的背景颜色。生成十六进制代码,但背景颜色不变。
我不确定Codepen是否限制了任何Bootstrap或颜色资源。我已经尝试过使用非引导按钮,但是它什么也没做。
来自Codepen.io的HTML
<main>
<div class="container">
<div class="row max-height align-items-center">
<div class="col-10 col-md-6 mx-auto text-center">
<h1 class=text-uppercase>hex color :<span id="hex-value"></span></h1>
<a href="#" id="btn" class="btn btn-secondary text-uppercase">click me</a>
</div>
</div>
</div>
</main>
在Codepen.io上运行的JS代码
function chgBkg() {
const button = document.querySelector('#btn')
const main = document.querySelector('main')
const hexValues = [0,1,2,3,4,5,6,7,8,9,'A','B','C','D','E','F']
const value = document.querySelector('#hex-value')
button.addEventListener('click',changeHex)
function changeHex() {
let hex = '#'
for (let i = 1; i < 6; i++) {
const index = Math.floor(Math.random()*hexValues.length)
hex += hexValues[index]
}
value.textContent = hex
main.style.backgroundColor = hex
}
}
chgBkg()
解决方法
为什么不尝试将锚链接更改为按钮元素?因为每次您单击没有链接的锚元素时,它都会自动重定向到同一页面,这意味着脚本也会刷新
,感谢@sol,从let i = 1
更改为let i = 0