如何使用 HTML、CSS 和 JavaScript 创建颜色选择器?

javascriptweb developmentfront end technology

我们可以轻松地在 Javascript 的调色板上创建一个简单的颜色选择器。颜色选择器上的原色是 RGB,即 红色、绿色和蓝色。通过混合这些颜色,我们可以形成任何我们想要的颜色。

在本文中,我们将学习如何从用户那里获取 RGB 值,并借助 CSS 使用 RGB 颜色属性形成不同的颜色。RGB 的颜色强度范围从 0 到 255,其中 0 是最小强度,255 是最高强度。

当所有 3 个冷却器的强度为 255 时,它会形成白色。当所有 3 个的强度均为 0 时,将形成黑色。

示例 1

在下面的示例中,我们借助基本的 HTML、CSS 和 JavaScript 创建了一个颜色选择器。

# index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <link rel="stylesheet" href="styles.css">
   <link href="https://fonts.googleapis.com/css2?family=Itim&display=swap"rel="stylesheet">
</head>
<body>
   <h1 style="color: green;">
      Welcome To Tutorials Point
   </h1>
   <div class="neumorphism-3"></div>
   <div class="input">
      <input type="number" id="red">
      <input type="number" id="green">
      <input type="number" id="blue">
   </div>
   <script src="script.js"></script>
</body>
</html>

# styles.css

.neumorphism-3 {
   width: 320px;
   height: 300px;
   box-shadow: -3px -3px 7px #e9e9e9a9,
      3px 3px 7px #e9e9e9a9;
}
.neumorphism-3:hover {
   top: 30px;
   box-shadow: -3px -3px 7px #999999a9,
      -3px -3px 12px #e9e9e9a9,
      3px 3px 7px #999999a9,
      -3px -3px 12px #e9e9e9a9;
   animation: uplift 0.1s 1 linear;
}
.neumorphism-3:not( :hover) {
   animation: downlift 0.1s 1 linear;
   top: 40px;
}
div.input {
   top: 450px;
   left: 550px;
}
div.input input {
   height: 30px;
   width: 100px;
   font-size: 30px;
   color: seashell;
   text-align: center;
   opacity: 0.7;
   border: none;
   border-radius: 4px;
}
#red {
   margin-top: 40px;
   background-color: red;
}
#green {
   background-color: green;
}
#blue {
   background-color: blue;
}

# script.js

let red = document.getElementById('red');
let green = document.getElementById('green');
let blue = document.getElementById('blue');
let box = document.querySelector('div.neumorphism-3');
let r = 0, g = 0, b = 0;
red.addEventListener("keyup", function (event) {
   r = red.value;
   if (!r)
      r = 0;
   box.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
});
green.addEventListener("keyup", function (event) {
   g = green.value;
   if (!g)
      g = 0;
   box.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
});
blue.addEventListener("keyup", function (event) {
   b = blue.value;
   if (!b)
      b = 0;
   box.style.backgroundColor = `rgb(${r}, ${g}, ${b})`;
});

输出

成功执行上述代码后,将生成一个颜色选择器。它显示一个矩形颜色窗格,以及 Redd、Green 和 Blue 三个输入。您输入特定的 RGB 值,相应的颜色就会出现在颜色窗格中。

当 RGB 为 0,0,0 时:

当 RGB 为 255,255,255 时:

我们有合并 HTML、CSS 和 JS 以帮助您在此处检查该程序的输出。

Click the following link to see a Live Demo of this program.


相关文章