javascript - 无法从文本框中获取用户输入以更改 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();
解决方案
这里发生了一些事情:
首先-您var inputVal = document.getElementById("box").value;
正在获得价值<div>
?我相信那行想读var inputVal = document.getElementById("colorInput").value;
第二 - 你<div>
试图改变当前的背景颜色占用 0px。您需要通过 CSS 给它一个大小,或者在<div></div>
标签之间放置一些内容。
推荐阅读
- mongodb - 如何将 MongoDB 中的数组更新为 Document 对象
- javascript - 我的 javascript 登录程序不工作
- android - Android Text To Speech - 突出显示口语
- java - 如何使条件StringUtils小于Java中的特定字符
- mongodb - 无法使用 MongoDB 更新嵌套对象值
- php - 如何修复php非法偏移错误
- java - Android studio-未能下载内容
- shopify - Shopify:如何在结账时使用 Bing 转化跟踪 (UET)?
- python - Django/Python Where to find a list of available filter functions when querying
- javascript - 如何防止搜索框崩溃?