使用js和css做一个滑块改变图片边距和高斯模糊的效果

这个案例我一开始以为要十几行代码才能完成,没想到用了几行代码就搞定了,重要原因是利用了css自定义属性,只需根据滑块滑动然后更改相应的属性值就可以了
demo:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<style>
:root{
--base:#67e6ff;
--spadding:10px;
--blur:10px;
}
img{
padding:var(--spadding);
background:var(--base);
filter:blur(var(--blur));
}
.hl {
color: 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>
<body>
<h2>Update CSS Variables with <span class='hl'>JS</span></h2>
<div class="controls">
<label form="padding">边距</label>
<input type="range" name="spadding" data-s="px" max="100" value="10"/>
<label form="blur">高斯模糊</label>
<input type="range" name="blur" data-s="px" max="100" value="10"/>
<label form="color">边框颜色</label>
<input type="color" name="base" />
</div>
<img src="./1.jpg" />
</body>
<script>
const inputs = document.querySelectorAll('.controls input')
function hand(){
const suffix = this.dataset.s || '';
document.documentElement.style.setProperty(`--${this.name}`, this.value + suffix);
}
inputs.forEach(input => input.addEventListener("change",hand));
inputs.forEach(input => input.addEventListener("mousemove",hand));
</script>
</html>
网友评论