【问题标题】:Why won't my background colour update with the generated hex value?为什么我的背景颜色不会用生成的十六进制值更新?
【发布时间】:2020-12-14 19:19:26
【问题描述】:

我希望每次单击按钮时都会在生成的十六进制代码旁边更新我的背景颜色。生成十六进制代码,但背景颜色不变。

我不确定 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()

【问题讨论】:

  • 试试let i = 0
  • 哦,伙计。那行得通。我觉得荒谬。非常感谢。

标签: javascript html css hex codepen


【解决方案1】:

为什么不尝试将锚链接更改为按钮元素?由于每次单击没有链接的锚元素时,它都会自动重定向到同一页面,这意味着脚本也会刷新

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-04-02
      • 2019-03-26
      • 2012-04-30
      • 2019-07-20
      • 1970-01-01
      • 2010-10-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多