按钮点击水波纹效果和两边扩散效果
作者:互联网
废话少说,先上代码了,复制到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" />
<title>Document</title>
<style>
.btn,
.btn2 {
position: relative;
width: 150px;
height: 60px;
background: #409eff;
outline: 0;
border: none;
padding: 12px 20px;
overflow: hidden;
color: #fff;
}
.btn::before,
.btn2::before {
content: '';
display: block;
position: absolute;
width: 100%;
height: 100%;
left: 0;
top: 0;
transition: 0.2s;
background: #fff;
opacity: 0;
}
.btn:active::before,
.btn2:active::before {
opacity: 0.2;
}
.btn::after {
content: '';
display: block;
position: absolute;
width: 200%;
height: 100%;
left: var(--x, 0);
top: var(--y, 0);
background-image: radial-gradient(circle, #fff 10%, transparent 10.01%);
background-repeat: no-repeat;
background-position: 50%;
transform: translate(-50%, -50%) scale(10);
opacity: 0;
transition: transform 0.8s, opacity 0.8s;
}
.btn:active::after {
transform: translate(-50%, -50%) scale(0);
opacity: 0.3;
transition: 0s;
}
.btn2::after {
content: '';
display: block;
position: absolute;
background: rgb(255, 255, 255, 0.7);
left: 0;
top: 0;
right: 0;
bottom: 0;
opacity: 0;
transition: all 0.8s, opacity 0.8s;
}
.btn2:active::after {
left: var(--l, 0);
right: var(--r, 0);
opacity: 0.3;
transition: 0s;
}
</style>
</head>
<body>
<!-- 水波纹扩散 -->
<button class="btn">水波纹散开</button>
<!-- 两边扩散 -->
<button class="btn2">两边散开</button>
</body>
<script>
(() => {
const el = document.querySelector('.btn');
el.addEventListener('mousedown', e => {
const { left, top } = el.getBoundingClientRect();
el.style = `--x:${e.clientX - left}px;--y:${e.clientY - top}px`;
});
const el2 = document.querySelector('.btn2');
el2.addEventListener('mousedown', e => {
const { left, right } = el2.getBoundingClientRect();
el2.style = `--l:${e.clientX - left}px;--r:${right - e.clientX}px`;
});
})();
</script>
</html>
原理,通过监听按下事件,获取到点击坐标,将获取到的坐标通过style代入到自定义变量中,css中写入相关样式,引用伪元素,只需改变点击坐标点即可
总结,网上水波纹的例子有许多,但很多都不完善,如连续点击后水波纹会失效,本文已优化,并通过自定义css变量来实现,相对于较简单
标签:水波纹,opacity,效果,--,background,按钮,btn,btn2,left 来源: https://www.cnblogs.com/ybchen292/p/16378432.html