如何在按钮上创建水波纹效果
水波纹效果是现代设计趋势的一部分。你在许多网站上都见过,尤其是谷歌的Material Design语言中。它给按钮产生按压效果。我们可以通过给按钮添加一个子元素并对其进行动画处理来创建水波纹效果。我们还可以使用JavaScript根据鼠标在按钮上的位置来定位它。
基本样式: 给按钮添加基本样式,使用position: relative属性来定位内部的span标签,并使用overflow: hidden属性来防止span超出按钮范围。
给span元素添加样式: 现在为span元素添加样式,它将在按钮点击时显示出来。
添加JavaScript代码: 现在我们将在按钮点击时添加span元素,并将其定位到鼠标点击的位置。在按钮点击事件中,我们需要执行以下操作:
- 创建一个span元素并为其添加一个ripple类。
- 使用事件变量获取鼠标点击的位置。
- 设置span元素的位置。
- 移除span元素,以避免在按钮上产生大量的span元素。
示例:
<!DOCTYPE html>
<html>
<head>
<title>
Button Ripple Effect - GFG
</title>
<style>
/* Adding styles to button */
.btn {
padding: 12px 50px;
border: none;
border-radius: 5px;
background-color: #1abc9c;
color: #fff;
font-size: 18px;
outline: none;
cursor: pointer;
/* We need this to position
span inside button */
position: relative;
overflow: hidden;
box-shadow: 6px 7px 40px -4px
rgba(0, 0, 0, 0.2);
}
</style>
</head>
<body>
<button class="btn">
Enter GeeksforGeeks
</button>
</body>
</html>
CSS代码
<style>
.btn span {
position: absolute;
border-radius: 50%;
/* To make it round */
background-color: rgba(0, 0, 0, 0.3);
width: 100px;
height: 100px;
margin-top: -50px;
/* for positioning */
margin-left: -50px;
animation: ripple 1s;
opacity: 0;
}
/* Add animation */
@keyframes ripple {
from {
opacity: 1;
transform: scale(0);
}
to {
opacity: 0;
transform: scale(10);
}
}
</style>
Javascript代码
<script>
const btn = document.querySelector(".btn");
// Listen for click event
btn.onclick = function (e) {
// Create span element
let ripple = document.createElement("span");
// Add ripple class to span
ripple.classList.add("ripple");
// Add span to the button
this.appendChild(ripple);
// Get position of X
let x = e.clientX - e.target.offsetLeft;
// Get position of Y
let y = e.clientY - e.target.offsetTop;
// Position the span element
ripple.style.left = `{x}px`;
ripple.style.top = `{y}px`;
// Remove span after 0.3s
setTimeout(() => {
ripple.remove();
}, 300);
};
</script>
输出: