首页 > 解决方案 > 如何通过使用 JS EventListener 的 HTML 表单的输入来更改 HTML 元素的背景颜色

问题描述

我对 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); 

标签: javascripthtmldom-events

解决方案


好吧,您需要读取该值,该值在您想要将其应用于样式时是实际/有效的:

<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


推荐阅读