使用波纹效果,以简单,优雅的方式为用户提供反馈。按钮不仅具有精美的波纹动画,而且动画还会根据每个按钮的单击位置而改变位置。
HTML的结构为:
<button>BUTTON</button>
按钮的样式效果为:
button {
position: relative;
overflow: hidden;
transition: background 400ms;
color: #fff;
background-color: #6200ee;
padding: 1rem 2rem;
font-family: 'Roboto', sans-serif;
font-size: 1.5rem;
outline: 0;
border: 0;
border-radius: 0.25rem;
box-shadow: 0 0 0.5rem rgba(0, 0, 0, 0.3);
cursor: pointer;
}
里面的波纹是通过JS动态创建的,我们需要给波纹写样式:
span.ripple {
position: absolute; /* 根据按钮定位 */
border-radius: 50%;
transform: scale(0);
animation: ripple 600ms linear;
background-color: rgba(255, 255, 255, 0.7);
}
@keyframes ripple {
to {
transform: scale(4);
opacity: 0;
}
}
波纹元素定义 .ripple
类名,最后通过JS注入到HTML中。
为了使波纹变圆,我们将其设置 border-radius
为50%。我们设置了比例为0,默认不显示波纹。现在,我们将无法看到任何东西,因为我们还没有为波浪设置 top,left,width,或 height 属性; 我们很快将使用 JavaScript 添加这些属性。
<body>
<button>BUTTON</button>
<script>
function createRipple(event) {
const button = event.currentTarget;
const circle = document.createElement("span");
const diameter = Math.max(button.clientWidth, button.clientHeight);
const radius = diameter / 2;
circle.style.width = circle.style.height = `${diameter}px`;
circle.style.left = `${event.clientX - button.offsetLeft - radius}px`;
circle.style.top = `${event.clientY - button.offsetTop - radius}px`;
circle.classList.add("ripple");
const ripple = button.getElementsByClassName("ripple")[0];
if (ripple) {
ripple.remove();
}
button.appendChild(circle);
}
const button = document.getElementsByTagName("button")[0];
button.addEventListener("click", createRipple);
</script>
</body>
1、我们将通过找到事件的 currentTarget 来访问我们的按钮。
2、接下来,我们将实例化 span 元素,并根据按钮的宽度和高度计算其直径和半径。
3、我们需要为我们的波浪效果添加其余属性:left,top,width 和 height。
4、在将 span 元素添加到 DOM 之前,最好检查一下以前的点击是否会留下现有的波浪,并在执行下一次单击之前将其删除。
5、完成我们的功能后,在页面上的按钮点击事件上添加波浪。