首页 > 解决方案 > 我如何在 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>

标签: javascripthtmlcss

解决方案


您需要获取输入的值,并在用户单击时执行。

您还需要删除其他颜色的类。

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>


推荐阅读