如何从输入中选择颜色后使此按钮更改背景颜色?
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>
答案 0 :(得分:1)
您应该将点击事件附加到按钮changeColor
,然后在此事件中执行颜色更改,例如:
var button = document.querySelector("#changeColor");
button.addEventListener("click", function() {
body.style.background = theInput.value;
}, false);
注意: form
内的按钮默认为提交按钮,因此您应添加type='button'
:
<button id="changeColor" type="button">Click me</button>
或e.preventDefault()
:
button.addEventListener("click", function(e) {
e.preventDefault()
body.style.background = theInput.value;
}, false);
单击后阻止表单提交和页面刷新。
希望这有帮助。
工作代码段
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>
答案 1 :(得分:1)
如果您想在用户输入颜色后立即更改按钮的颜色,请将事件监听器从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>
&#13;
答案 2 :(得分:1)
var theInput = document.getElementById("favColor");
var body = document.querySelector("body");
var theColor = theInput.value;
function changeColor() {
body.style.background = theInput.value;
}
&#13;
<input type="color" name="colorChange" value="" id="favColor">
<button id="changeColor" onclick="changeColor()">Click me</button>
&#13;