javascript - 如何通过使用 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);
解决方案
好吧,您需要读取该值,该值在您想要将其应用于样式时是实际/有效的:
<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>
推荐阅读
- python - 气流 SSH 操作员错误,意外的关键字参数
- c++ - Visual Studio 2017 上的 NuGet 包“opencvdefault”链接错误
- angular - 具有 Windows 身份验证的 .NetCore 2.2 Web Api 从其他域返回 401
- r - 如何用 stringr 中的 str_replace 替换插入符号
- docker - 有人能告诉我如何使用 .git-ci.yml 文件在 gcloud kubernetes 集群上部署 kaniko 构建的 docker 映像吗?
- azure-devops - 将来自 Azure devops 的 jacoco 代码覆盖率报告集成到代码气候
- c - 如何修复 GDB 找不到文件:“../sysdeps/unix/sysv/linux/raise.c:50”
- ruby-on-rails - 让国家和城市进入铁路
- c++ - 动态迭代静态信息
- java - 使用自定义类作为 HashMap 中的键,但无法搜索键