使用 JavaScript 时,onchange 事件在颜色类型输入中不起作用

javascriptweb developmentobject oriented programming更新于 2025/8/21 14:04:17

当元素发生变化时,onchange 事件会触发。您需要使用以下语法。

onchange="yourFunctionName(this);"

示例

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>
<body>
<p>
<label for="color">选择颜色</label> <input type="color" id="selectedColor"
value="#985d5d" onchange="showValue(this);" />
</p>
<script>
   function showValue(c){
      console.log(c.value);
   }
</script>
</body>
</html>

要运行上述程序,请保存文件名 anyName.html(index.html),然后右键单击该文件并选择在 VS 代码编辑器中使用实时服务器打开选项。

输出

点击输入类型颜色后,您将在控制台中获得颜色值 −


相关文章


有用资源