首页 > 解决方案 > 无法从文本框中获取用户输入以更改 Javascript 中的框背景颜色

问题描述

我正在尝试从文本框中获取用户输入以更改我的作业的背景框颜色。我已经玩了一段时间了,但是,它仅在我将框值设置为 colorInput 时才有效。

document.getElementById("box").value;
document.getElementById("box").value;

HTML:

<label for="colorInput">Enter a Color:</label>
        <input id="colorInput" type="text">
        <button id="submitColor" type="button">Submit Color</button>
        <div id="box" class="box"></div>

Javascript:

/** Question 2 */
function submitColor() {
    document.getElementById("submitColor").onclick = function() {
        var inputVal = document.getElementById("box").value;
        if (inputVal.value == "yellow") {
            document.getElementById("box").style.backgroundColor = "yellow";
        } else if(inputVal.value == "red") {
            document.getElementById("box").style.backgroundColor = "red";
        }

    }
}
submitColor();

标签: javascripthtml

解决方案


这里发生了一些事情:

首先-您var inputVal = document.getElementById("box").value;正在获得价值<div>?我相信那行想读var inputVal = document.getElementById("colorInput").value;

第二 - 你<div>试图改变当前的背景颜色占用 0px。您需要通过 CSS 给它一个大小,或者在<div></div>标签之间放置一些内容。


推荐阅读