HTML无法获取输入颜色值

HTML Cannot Get Input Color Value

本文关键字:输入 颜色值 获取 HTML      更新时间:2023-09-26

我试图在HTML中获得颜色输入,并且我无法获得用户选择的值。这是我的代码:

function setColor() {
  alert(document.getElementById("colorPicker").value)
}
<button type="button" onclick="setColor()">Set Color</button>
<input type="color" name="colorPicker" value="#ff0000">

您试图通过其ID(即getElementById())选择input,但该元素没有ID,只有名称。更新您的<input />以包括id属性,如下所示:

function setColor() 
{
	alert(document.getElementById("colorPicker").value)
}
<button type="button" onclick="setColor()">Set Color</button>
<input type="color" id="colorPicker" name="colorPicker" value="#ff0000" />

没有id为"colorPicker"的元素。你应该设置输入id="colorPicker"而不是

<html>
<head>
<script>
function setColor() {
alert(document.getElementById("colorPicker").value)
}
</script>
</head>
<body bgcolor="#808080">
<button type="button" onclick="setColor()">Set Color</button>
<input type="color" name="colorPicker" id="colorPicker" value="#ff0000">
</body>
</html>

你的代码中有几处错误

    你已经创建了一个button类型的按钮2.把你的标记和javascript混在一起不是一个好习惯。

检查以下代码片段

window.onload=function(){
  var el = document.getElementById("button1");
el.addEventListener("click", setColor);
}
function setColor() {
alert(document.getElementById("colorPicker").value);
}
<body bgcolor="#808080">
<input type="button" id="button1"  value="Set Color"></input>
<input type="color" id="colorPicker" value="#ff0000">
</body>

为输入元素添加一个带有'colorPicker'值的'id'属性。

似乎你试图通过使用'getElementById'来选择输入,它实际上没有id