按钮小特效
通过js与css的配合可以非常方便的实现一些简单的小特效。这里记录一个按钮点击出现扩散的动画特效。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.wrap-btn {
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
height: 150px;
}
button {
outline: none;
padding: 0px 32px;
line-height: 40px;
border-radius: 8px;
color: #fff;
border: 0;
margin: 20px 0;
position: relative;
overflow: hidden;
background-image: linear-gradient(90deg, rgba(233, 54, 224, 0.877), rgba(187, 79, 230, 0.678));
}
button:nth-of-type(2) {
background-image: linear-gradient(90deg, rgba(73, 103, 235, 0.89), rgba(187, 79, 230, 0.678));
}
.wave-btn span {
position: absolute;
display: inline-block;
background-color: #fff;
animation: wave .6s ease-out infinite;
transform: translate(-50%, -50%);
border-radius: 50%;
}
@keyframes wave {
0% {
width: 0;
height: 0;
opacity: .5;
}
100% {
width: 200px;
height: 200px;
opacity: 0;
}
}
</style>
</head>
<body>
<div class="wrap-btn">
<button class="btn wave-btn">button</button>
<button class="wave-btn">button</button>
</div>
</body>
<script>
// 通过事件委托将加入移除子元素委托到document上,之后就可以只对需要使用此特效的按钮添加一个wave-btn的class就可以了
document.onclick = e => {
const target = e.target || e.srcElement;
if (target.className.includes('wave-btn')) {
const btn = target;
const left = btn.offsetLeft;
const top = btn.offsetTop;
const x = e.clientX - left;
const y = e.clientY - top;
const span = document.createElement('span')
span.style = `left: ${x}px; top: ${y}px`;
btn.appendChild(span);
// 延时移除添加的子元素
setTimeout(() => { span.remove() }, 600)
}
}
</script>