介绍
相信做过前端开发的小伙伴们对渐变色在 UI 设计中的流行度一定不陌生,网页上也时常可以看到各类复杂的渐变色生成工具。使用原生的 CSS 变量加一些 JS 函数就能做出一个简单的渐变色背景生成器。
现在渐变色生成器只完成了颜色选取的功能,需要大家帮忙把取色器中的两个色值通过 JS 函数更新给 CSS 变量,从而实现渐变色预览功能。
准备
本题已经内置了初始代码,打开实验环境,目录结构如下:
├── index.html
├── index.js
└── styles.css
其中:
- styles.css 是页面样式文件。
- index.html 是页面布局结构。
- index.js 是页面功能实现的 js 文件。
选中 index.html 右键启动 Web Server 服务(Open with Live Server),让项目运行起来。
接着,打开环境右侧的【Web 服务】,就可以在浏览器中看到如下效果:
目标
目前的色块和渐变色背景为初始值且不会自动更新。
请大家根据 index.js 文件中的提示和要求添加所需的 JavaScript 代码,让色块的输入值对应到渐变色背景中,并且在更改色块颜色之后,渐变色背景也会随之改变
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" />
<title>Gradient Generator</title>
</head>
<body>
<div class="controls">
<input id="color1" type="color" name="color1" value="#00dbde" />
<input id="color2" type="color" name="color2" value="#fc00ff" />
</div>
<div class="gradient"></div>
<script src="index.js"></script>
</body>
</html>
css
/* 注意这里定义的 CSS 变量,它们会用于生成渐变色背景 */
:root {
--color1: #00dbde;
--color2: #fc00ff;
}
body {
width: 100vw;
height: 100vh;
overflow: hidden;
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
background: #222;
}
.controls {
width: 500px;
height: 100px;
display: flex;
justify-content: space-between;
}
input[type="color"] {
-webkit-appearance: none;
border: none;
width: 60px;
height: 60px;
border-radius: 5px;
}
input[type="color"]::-webkit-color-swatch-wrapper {
padding: 0;
margin: 0;
}
input[type="color"]::-webkit-color-swatch {
border: none;
border-radius: 5px;
transform: scale(1.1);
}
.gradient {
width: 500px;
height: 500px;
border-radius: 5px;
background: linear-gradient(45deg, var(--color1), var(--color2));
}
js
const inputs = document.querySelectorAll(".controls input");
/**
* 上面已经选取了两个取色器
* 请添加相应的 JS 事件处理函数并绑定到合适的事件监听器上(提示:change 事件)
* 这样我们就可以用取色器选取颜色来生成下方的渐变色背景啦
* */
知识点
setProperty() 方法:用于设置一个新的 CSS 属性,同时也可以修改 CSS 声明块中已存在的属性。
object.setProperty(propertyname, value, priority)
- propertyname 必需。一个字符串,表示创建或修改的属性。
- value 可选,新的属性值。
- priority 可选。字符串,规定是否需要设置属性的优先级 important。
- 可以是下面三个值:
- “important”
- undefined
- “”
- 可以是下面三个值:
答案
const inputs = document.querySelectorAll(".controls input");
/**
* 上面已经选取了两个取色器
* 请添加相应的 JS 事件处理函数并绑定到合适的事件监听器上(提示:change 事件)
* 这样我们就可以用取色器选取颜色来生成下方的渐变色背景啦
* */
const root = document.querySelector(":root");
for(let i = 0; i < inputs.length; i++)
{
inputs[i].addEventListener('change',function(){
root.style.setProperty("--color" + (i + 1), this.value);
})
}