简体   繁体   English

为什么我的背景颜色不会用生成的十六进制值更新?

[英]Why won't my background colour update with the generated hex value?

I'm hoping to update my background colour alongside the generated hex code each time I click on the button.我希望每次单击按钮时都会在生成的十六进制代码旁边更新我的背景颜色。 The hex code generates but the background colour does not change.十六进制代码生成但背景颜色不会改变。

I am not sure if Codepen limits any Bootstrap or colour resources.我不确定 Codepen 是否限制任何 Bootstrap 或颜色资源。 I've tried using a non-bootstrap button and that doesn't do anything.我试过使用非引导按钮,但没有任何作用。

HTML from Codepen.io来自 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>

JS Code running on Codepen.io在 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()

Why not try changing the anchor link to a button element?为什么不尝试将锚链接更改为按钮元素? Since every time you clicked an anchor element without a link in it will automaticaly redirect to the same page that means the script will also refresh由于每次单击没有链接的锚元素时,它都会自动重定向到同一页面,这意味着脚本也会刷新

感谢@sol,从let i = 1更改为let i = 0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM