admin管理员组文章数量:1303335
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 01 Answer
Reset to default 10change
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
andchange
.input
is fired on the<input>
element every time the color changes. Thechange
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 itsvalue
.
(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">
本文标签: javascriptSee how the color is being changed with input typecolorStack Overflow
版权声明:本文标题:javascript - See how the color is being changed with input type=color - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741754099a2396008.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论