最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - See how the color is being changed with input type=color - Stack Overflow

programmeradmin1浏览0评论

I want to see the color being changed while I am changing it. I do not want to click somewhere else to see the results.

Like in inspect element, we can change the color and watch it live.

How is it being changed and how to do this with JavaScript and the DOM?

I tried addEventListener("mousemove"), addEventListener("mousedown"), and addEventListener("change").

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">

I want to see the color being changed while I am changing it. I do not want to click somewhere else to see the results.

Like in inspect element, we can change the color and watch it live.

How is it being changed and how to do this with JavaScript and the DOM?

I tried addEventListener("mousemove"), addEventListener("mousedown"), and addEventListener("change").

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">

As you can see in my sample code, the color is not changing in live mode when I am changing the color in the color picker. After changing the color, I have to click anywhere else and then the color changes.

I want it to behave like in the gif above, I want to make color changes and see the changes at the same time.

Share Improve this question edited Sep 20, 2024 at 7:25 PeterJames 1,3533 gold badges11 silver badges21 bronze badges asked Feb 5, 2021 at 15:01 AltroAltro 9383 gold badges11 silver badges28 bronze badges 0
Add a ment  | 

1 Answer 1

Reset to default 10

change is only triggered when the dialogue is closed.
You want input instead:

Tracking color changes

As is the case with other <input> types, there are two events that can be used to detect changes to the color value: input and change. input is fired on the <input> element every time the color changes. The change event is fired when the user dismisses the color picker. In both cases, you can determine the new value of the element by looking at its value.

(Source: MDN | <input type="color"> -> Tracking color changes)

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">

发布评论

评论列表(0)

  1. 暂无评论