03-CSS Variables
功能主要就是当鼠标滑动的时候,改变相应的边框值、清晰度以及背景颜色
效果图:
主要代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Scoped CSS Variables and JS</title>
</head>
<body>
<h2>Update CSS Variables with <span class='hl'>JS</span></h2>
<div class="controls">
<label for="spacing">Spacing:</label>
<input id="spacing" type="range" name="spacing" min="10" max="200" value="10" data-sizing="px" data-sizing="px">
<label for="blur">Blur:</label>
<input id="blur" type="range" name="blur" min="0" max="25" value="10" data-sizing="px" data-sizing="px">
<label for="base">Base Color</label>
<input id="base" type="color" name="base" value="#ffc600">
</div>
<img src="https://source.unsplash.com/7bwQXzbF6KE/800x500">
<style>
/* 下面的两个都是css的自定义属性 */
.root{
--spacing:5px;
--blur:2px;
--base:yellow
}
img{
padding: var(--spacing);
filter: blur(var(--blur));
background: var(--base);
}
/* -------------- */
body {
text-align: center;
background: #193549;
color: white;
font-family: 'helvetica neue', sans-serif;
font-weight: 100;
font-size: 50px;
}
.controls {
margin-bottom: 50px;
}
input {
width: 100px;
}
</style>
<script>
// 这是第一种写法,虽然这种写法能够实现功能,但是这种写法也会产生弊端,如果我们在调用函数updateInput的时候需要多次判断就很繁琐,所以引出第二种写法如下:
// // 首先获取所有的input标签
// const input =document.querySelectorAll('.controls input')
// // 获取图片
// const img =document.querySelector('img')
// // 函数判断如果是边框改变则改变padding,如果是背景颜色改变则改变background,如果是清晰度则改变blur
// function updateInput(){
// if(this.name==='spacing'){
// img.style.padding =this.value+'px'
// }
// if(this.name === 'blur'){
// img.style.filter=`blur(${this.value}px)`
// }
// if(this.name === 'base'){
// img.style.background =this.value
// }
// }
// // 监听当input框内元素发生改变
// input.forEach(input =>input.addEventListener('change',updateInput))
// 这是第二种写法 首先需要在style中添加root
const input =document.querySelectorAll('.controls input')
const img =document.querySelector('img')
function updateInput(){
const str=this.dataset.sizing || ''
// setProperty设置的是内联样式,有三个参数,但是一般来讲只写两个参数即可,第三个参数是改变优先级的
document.documentElement.style.setProperty(`--${this.name}`,this.value+str)
// documentElement:一个元素对象返回一个文档的文档元素。
}
input.forEach(input =>input.addEventListener('change',updateInput))
</script>
</body>
</html>