英文 | https://www.geeksforgeeks.org/how-to-create-a-ripple-effect-on-click-the-button/?ref=leftbar-rightbar
翻译 | web前端开发(ID:web_qdkf)
波纹效过是现代设计趋势的一部分。你一定在许多网站上见到过,它提供了按钮按下的波纹动画效果。我们可以通过向按钮添加子元素并设置动画效果来产生涟漪效果。我们也可以使用Javascript根据光标在按钮上的位置进行定位。
1、基本样式:使用position:relative属性向按钮添加基本样式,以放置内部span标签并overflow:hidden防止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>
输出:
2、向span元素添加样式:现在为span元素添加样式,该样式将在单击按钮时显示。
<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>
3、添加JavaScript:现在,我们将在按钮单击上添加span元素,并根据鼠标单击的位置进行添加。在按钮上单击,我们必须执行以下操作:
创建span元素并向其添加波纹类。
使用event变量获取光标的点击位置。
设置span元素的位置。
删除span元素,以避免在按钮中出现span元素。
<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>
最终输出如下所示: