javascript - 我如何在 javascript 中正确使用价值
问题描述
你好,我是初学者,我想用 html、css 和 java 脚本制作一个小游戏,游戏是我有一个输入和按钮以及一个 div(框),我想在输入中写一个颜色(红色,蓝色,绿色和黄色)然后单击按钮,因此背景色 div(框)将更改
var myInput = document.getElementById('input-test'),
myButton = document.getElementById('button-test'),
myColor = document.getElementById('color-test');
if (myInput === "blue") {
myButton.onclick = function() {
'use strict';
myColor.classList.add('blue');
};
} else if (myInput == "red") {
myButton.onclick = function() {
'use strict';
myColor.classList.add('red');
};
}
.in {
margin-top: 50px;
height: 40px;
width: 100px;
border-radius: 10px;
border: 2px solid;
}
.vo {
height: 50px;
width: 100px;
border-radius: 20px;
}
.go {
height: 100px;
width: 100px;
background-color: black;
margin-top: 5px;
border-radius: 20px;
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
.green {
background-color: green;
}
.yellow {
background-color: yellow;
}
<input id="input-test" class="in" type="text" placeholder="Write the color" value="blue">
<button id="button-test" class="vo">click</button>
<div id="color-test" class="go"></div>
解决方案
您需要获取输入的值,并在用户单击时执行。
您还需要删除其他颜色的类。
var myInput = document.getElementById('input-test'),
myButton = document.getElementById('button-test'),
myColor = document.getElementById('color-test');
myButton.onclick = function() {
if (myInput.value == "blue") {
myColor.classList.add('blue');
myColor.classList.remove('red');
} else if (myInput.value == "red") {
myColor.classList.add('red');
myColor.classList.remove('blue');
};
}
.in {
margin-top: 50px;
height: 40px;
width: 100px;
border-radius: 10px;
border: 2px solid;
}
.vo {
height: 50px;
width: 100px;
border-radius: 20px;
}
.go {
height: 100px;
width: 100px;
background-color: black;
margin-top: 5px;
border-radius: 20px;
}
.red {
background-color: red;
}
.blue {
background-color: blue;
}
.green {
background-color: green;
}
.yellow {
background-color: yellow;
}
<input id="input-test" class="in" type="text" placeholder="Write the color" value="blue">
<button id="button-test" class="vo">click</button>
<div id="color-test" class="go"></div>
推荐阅读
- reactjs - 使用 Firebase 存储 + useEffect hook + useState hook 渲染图像时遇到问题
- http - 如何使用 HTTP.jl 获取客户端 IP 地址
- javascript - “d3.select(...) 不是函数”
- python - (Flask)如何在 html 中创建一个 If 语句来检测 for 循环中的最后一项
- ios - 开发依赖于原生框架的 react-native 库
- javascript - 同步 XMLHttpRequest 问题
- python - 过滤 Tweepy 流的问题
- c++ - 使用 clang CMake 包含 Boost 构建
- java - 如果假设一个接口是完全抽象的,为什么这段代码可以工作?
- vba - 为什么无法访问公共网站?