【问题标题】:How to change backgroundcolor of HTML element by using input from HTML form using JS EventListener如何使用 JS 事件侦听器使用来自 HTML 表单的输入来更改 HTML 元素的背景颜色
【发布时间】: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


【解决方案1】:

嗯,你需要读取值,在你想将它应用到样式时是实际/有效的:

<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

【讨论】:

    【解决方案2】:

    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>

    你需要做这样的事情。还建议检查输入是否为有效颜色。

    【讨论】:

      猜你喜欢
      • 2020-07-08
      • 2018-08-21
      • 2013-04-13
      • 2021-03-31
      • 1970-01-01
      • 2013-06-15
      • 2013-02-02
      • 1970-01-01
      • 2017-07-06
      相关资源
      最近更新 更多