我是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);
好吧,你需要读取值,在当时是实际的/有效的。你想把它应用到样式:
<script >
const inputColor = () => document.getElementById("task3Input").value.toString();
const taskThreeContainer = () => document.getElementById("taskThreeContainer");
function convertColor() {
console.log(inputColor())
taskThreeContainer().style.backgroundColor = `${inputColor()}`;
};
document.getElementById("task3Input").addEventListener("blur", convertColor);
</script>
https://plnkr.co/edit/0U8s8a4NUciwTgGt?open=lib%2Fscript.js
function getColor() {
let color = document.forms["colorForm"]["color"].value;
documen.getElementById("changeable_element").style.color = color;
}
<div id="changable_element">Something...</div>
<form name="colorForm" onsumit="getColor()">
<input type="text" name="color"/>
<input type="submit" name="Submit"/>
</form>
你需要做这样的东西。它还建议检查输入的颜色是否有效。