javascript 如何找到输入的值?

fnvucqvd  于 2023-04-19  发布在  Java
关注(0)|答案(5)|浏览(75)

我如何使盒子的颜色成为输入的值?

box = document.getElementById("box");
typeColor = document.getElementById("typeColor");

function changeBoxColor() {
  box.style.backgroundColor = typeColor;
}
  
//box is a div, typeColor is an input
body {
  margin: 0px;
}

#box {
  width: 100px;
  height: 100px;
  background-color: grey;
  margin-left: 100px;
  margin-top: 50px;
}
<input id="typeColor" placeholder="Type a color...">
<button onclick="changeBoxColor()">Change Box Color</button>
<div id="box">
</div>
68bkxrlz

68bkxrlz1#

为什么要让它简单,当你可以让它非常复杂?

const 
  box     = document.getElementById('box')
, btColor = document.getElementById('btColor')
  ;

btColor.onchange = () => 
  {
  box.style.backgroundColor = btColor.value;
  }
#box {
  width       : 100px;
  height      : 100px;
  background  : red;
  margin-left : 100px;
  margin-top  : 50px;
  }
<input id="btColor" type="color" value="#FF0000"> 
 
<div id="box">
</div>
idv4meu8

idv4meu82#

按如下所示更改颜色设置行。

box.style.backgroundColor = typeColor.value;
box = document.getElementById("box");
typeColor = document.getElementById("typeColor");

function changeBoxColor() {
  box.style.backgroundColor = typeColor.value;
}
body {
  margin: 0px;
}

#box {
  width: 100px;
  height: 100px;
  background-color: grey;
  margin-left: 100px;
  margin-top: 50px;
}
<input id="typeColor" placeholder="Type a color...">
<button onclick="changeBoxColor()">Change Box Color</button>
<div id="box">
</div>
368yc8dk

368yc8dk3#

下面是一个工作代码片段

box = document.getElementById("box");
typeColor = document.getElementById("typeColor");

function changeBoxColor() {
  box.style.backgroundColor = typeColor.value;
}
body {
  margin: 0px;
}

#box {
  width: 100px;
  height: 100px;
  background-color: grey;
  margin-left: 100px;
  margin-top: 50px;
}
<input type="color" id="typeColor" placeholder="Type a color...">
<button onclick="changeBoxColor()">Change Box Color</button>
<div id="box">
</div>
zaqlnxep

zaqlnxep4#

你可以简单地在输入框中输入文本,在你的代码中而不是typeColor,请使用typeColor。value你可以用那个框上提供的颜色名称来填充这个框。
谢谢大家。

box = document.getElementById("box");
typeColor = document.getElementById("typeColor");

function changeBoxColor() {
  box.style.backgroundColor = typeColor.value;
}
  
//box is a div, typeColor is an input
body {
  margin: 0px;
}

#box {
  width: 100px;
  height: 100px;
  background-color: grey;
  margin-left: 100px;
  margin-top: 50px;
}
<input id="typeColor" placeholder="Type a color..." value="Red">
<button onclick="changeBoxColor()">Change Box Color</button>
<div id="box">
</div>
b91juud3

b91juud35#

value属性设置或返回输入标记字段的value属性的值。

语法

返回value属性:

let returnValue = inputObject.value

设置值属性:

let someNumber = 23;
inputObject.value = someNumber

转移到您的代码示例:

box = document.getElementById("box");
typeColor = document.getElementById("typeColor");

function changeBoxColor() {
  box.style.backgroundColor = typeColor.value;
}
//box is a div, typeColor is an input

更多信息可以在here中找到

相关问题