[英]How can I make this button change the background color after selecting color from the input?
How can I make this button change the background color after selecting color from the input?? 从输入中选择颜色后,如何使此按钮更改背景颜色?
var theInput = document.getElementById("favColor"); var body = document.querySelector("body"); var theColor = theInput.value; theInput.addEventListener("change", function() { body.style.background = theInput.value; }, false);
<form> <input type="color" name="colorChange" value="" id="favColor"> <button id="changeColor">Click me</button> </form>
You should attach a click event to the button changeColor
then perform the color change inside this event, like : 您应该将click事件附加到按钮
changeColor
然后在此事件中执行颜色更改,如:
var button = document.querySelector("#changeColor");
button.addEventListener("click", function() {
body.style.background = theInput.value;
}, false);
NOTE : A button inside form
is by default a submit button, so you should add type='button'
: 注意:
form
内的按钮默认为提交按钮,因此您应该添加type='button'
:
<button id="changeColor" type="button">Click me</button>
Or e.preventDefault()
: 或者
e.preventDefault()
:
button.addEventListener("click", function(e) {
e.preventDefault()
body.style.background = theInput.value;
}, false);
To prevent the form submit and page refresh after the click. 单击后阻止表单提交和页面刷新。
Hope this helps. 希望这可以帮助。
Working snippet : 工作片段:
var theInput = document.getElementById("favColor"); var body = document.querySelector("body"); var button = document.querySelector("#changeColor"); button.addEventListener("click", function() { body.style.background = theInput.value; }, false);
<form> <input type="color" name="colorChange" value="" id="favColor"> <button id="changeColor" type="button">Click me</button> </form>
If you want the color of the button to change as soon as the user types the color in, change the event listener from change
to keyUp
like such: 如果您希望在用户键入颜色后立即更改按钮的颜色,请将事件侦听器从
change
为keyUp
如下所示:
<form> <input type="color" name="colorChange" value="" id="favColor"> <button id="changeColor">Click me</button> </form> <script type="text/javascript"> var theInput = document.getElementById("favColor"); var body = document.querySelector("body"); var theColor = theInput.value; theInput.addEventListener("keyup", function() { document.getElementById("changeColor").style.background = theInput.value; }, false); </script>
var theInput = document.getElementById("favColor"); var body = document.querySelector("body"); var theColor = theInput.value; function changeColor() { body.style.background = theInput.value; }
<input type="color" name="colorChange" value="" id="favColor"> <button id="changeColor" onclick="changeColor()">Click me</button>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.