波纹效过是现代设计趋势的一部分。你一定在许多网站上见到过,它提供了按钮按下的波纹动画效果。我们可以通过向按钮添加子元素并设置动画效果来产生涟漪效果。我们也可以使用Javascript根据光标在按钮上的位置进行定位。
一、基本样式:使用position:relative属性向按钮添加基本样式,以放置内部span标签并overflow:hidden防止span超出按钮。
<!DOCTYPE html>
<html>
<head>
<title></title>
<style>
/* 为按钮添加样式 */
.btn {
padding: 12px 50px;
border: none;
border-radius: 5px;
background-color: #1abc9c;
color: #fff;
font-size: 18px;
outline: none;
cursor: pointer;
/* 我们需要这个来定位span在按钮内部 */
position: relative;
overflow: hidden;
box-shadow: 6px 7px 40px -4px rgba(0, 0, 0, 0.2);
}
</style>
</head>
<body>
<button class="btn">
Click On The Button
</button>
</body>
</html>
效果:
二、向span元素添加样式:现在为span元素添加样式,该样式将在单击按钮时显示。
.btn span {
position: absolute;
border-radius: 50%;
background-color: rgba(0, 0, 0, 0.3);
width: 100px;
height: 100px;
margin-top: -50px;
margin-left: -50px;
animation: ripple 1s;
opacity: 0;
}
@keyframes ripple {
from {
opacity: 1;
transform: scale(0);
}
to {
opacity: 0;
transform: scale(10);
}
}
三、添加JavaScript:现在,我们将在按钮单击上添加span元素,并根据鼠标单击的位置进行添加。在按钮上单击,我们必须执行以下操作:
- 创建span元素并向其添加波纹类。
- 使用event变量获取光标的点击位置。
- 设置span元素的位置。
- 删除span元素,以避免在按钮中出现span元素。
<script>
const btn = document.querySelector(".btn");
// 监听单击事件
btn.onclick = function(e) {
// 创建span元素
let ripple = document.createElement("span");
// 向span添加ripple类
ripple.classList.add("ripple");
// 向按钮添加span
this.appendChild(ripple);
// 获得X的位置
let x = e.clientX - e.target.offsetLeft;
// 获得Y位置
let y = e.clientY - e.target.offsetTop;
ripple.style.left = `${x}px`;
ripple.style.top = `${y}px`;
setTimeout(() => {
ripple.remove();
}, 300);
};
</script>