英文 | 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>
最終輸出如下所示: