[英]How do I change the background of my body when picking a color from my input with the type=“color”
I have tried adding a onclick event that when clicked changes the background to whatever is set in my input field but it did not work.我尝试添加一个 onclick 事件,当单击该事件时,该事件将背景更改为我输入字段中设置的任何内容,但它不起作用。 I do not know if I am using a wrong event or if it is something else.
我不知道我是否使用了错误的事件,或者它是否是其他东西。 Can someone please help me thank you.
有人可以帮我吗谢谢。
let color = document.getElementById("color-picker"); color.addEventListener("click", function() {colorPicker(color)}); function colorPicker(chooseColor) { body.style.backgroundColor = chooseColor }
<fieldset> <legend>Appearing here</legend> <div> <label for="color-picker">Colors</label> </div> <div> <input type="color" id="color-picker"> </div> </fieldset>
A few issues几个问题
change
event should be used instead of click
change
事件而不是click
document.body
instead of body
document.body
而不是body
chooseColor.value
to pick the value of the color pickerchooseColor.value
来选择颜色选择器的值 let color = document.getElementById("color-picker"); color.addEventListener("input", function() {colorPicker(color)}); function colorPicker(chooseColor) { document.body.style.backgroundColor = chooseColor.value; }
<fieldset> <legend>Appearing here</legend> <div> <label for="color-picker">Colors</label> </div> <div> <input type="color" id="color-picker"> </div> </fieldset>
You can simplify this by putting the addEventListener
function all on one line (using an arrow =>
function, and using an onChange
event, not onClick
. Then you want to return color.value
, not the input element color
itself. Finally, you want to use document.body
, not body
: You can simplify this by putting the
addEventListener
function all on one line (using an arrow =>
function, and using an onChange
event, not onClick
. Then you want to return color.value
, not the input element color
itself. Finally, you want使用document.body
,而不是body
:
let color = document.getElementById("color-picker") color.addEventListener("change",() => document.body.style.backgroundColor = color.value)
<fieldset> <legend>Appearing here</legend> <div> <label for="color-picker">Colors</label> </div> <div> <input type="color" id="color-picker"> </div> </fieldset>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.