查看输入类型=颜色如何改变颜色

问题描述 投票:0回答:1

我想在更改颜色时看到颜色发生变化。我不想点击其他地方来查看结果。

就像在检查元素中一样,我们可以更改颜色并实时观看。

它是如何改变的以及如何使用 JavaScript 和 DOM 来做到这一点?

我尝试了

addEventListener("mousemove")
addEventListener("mousedown")
addEventListener("change")

enter image description here

document.getElementById("b").addEventListener("change",function(e){
  document.getElementById("a").style.backgroundColor = e.target.value;
})
#a {
  width: 100px;
  height: 100px;
  background-color: black;
}
<div id="a"></div>
<input type="color" id="b">

正如您在我的示例代码中看到的,当我更改颜色选择器中的颜色时,实时模式下的颜色没有变化。改变颜色后,我必须点击其他地方,然后颜色就会改变。

我希望它的行为像上面的 gif 一样,我想改变颜色并同时看到变化。

javascript html css
1个回答
9
投票

change
仅在对话框关闭时触发。
您想要
input
来代替:

跟踪颜色变化

与其他

<input>
类型一样,有两个事件可以 用于检测颜色值的变化:
input
change
input
每次颜色变化时都会在
<input>
元素上触发。这 当用户关闭颜色选择器时会触发
change
事件。在 在这两种情况下,您都可以通过查看来确定元素的新值 在其
value

(来源:MDN |

<input type="color">
-> 跟踪颜色变化

document.getElementById("b").addEventListener("input", function() {
  console.log(this.value);
  document.getElementById("a").style.backgroundColor = this.value;
})
#a {
  width: 100px;
  height: 100px;
  background-color: black;
}
<div id="a"></div>
<input type="color" id="b">

© www.soinside.com 2019 - 2024. All rights reserved.