【发布时间】:2021-10-20 10:10:23
【问题描述】:
我是 JS 的新手,我在使用来自 HTML 表单和事件侦听器的输入来更改 HTML 元素的背景时遇到了麻烦。这是我迄今为止尝试过的:
HTML:
<div class="item" id="taskThreeContainer">
<h2>Task 3</h2>
<p>When writing a valid CSS background color in the input below, the background of this item should change to that color.</p>
<input type="text" id="task3Input">
<script src="script.js" async defer></script>
JS:
//Task 3
const inputColor = document.getElementById("task3Input").value;
const taskThreeContainer = document.getElementById("taskThreeContainer");
function convertColor() {
taskThreeContainer.style.backgroundColor = inputColor;
};
document.getElementById("task3Input").addEventListener("input", convertColor);
任何帮助将不胜感激
解决方案(JS):
//Task 3
const taskThreeContainer = document.getElementById("taskThreeContainer");
function convertColor() {
const inputColor = document.getElementById("task3Input").value.toString();
taskThreeContainer.style.backgroundColor = inputColor;
};
document.getElementById("task3Input").addEventListener("input", convertColor);
【问题讨论】:
-
您尝试读取输入值,甚至还没有输入值。访问值属于 inout 处理函数的内部。
-
@CBroe 谢谢,这有效!我通过将 taskThreeContainer 移动到输入处理函数 convertColor 来解决它:)
标签: javascript html dom-events