css3+js實現按鈕水紋漣漪效果

css3+js實現按鈕水紋漣漪效果

HTML

  • 首先我們用<a>標籤定義兩個按鈕
<a href="#">button</a>
<a href="#">button</a>

CSS3

  • 調整佈局樣式
  • 色彩範圍
* {
    margin: 0;
    padding: 0;
    font-family: 'Poppins', sans-serif; /* 字體 */
}

body {
    display: flex;
    justify-content: center;/* 彈性盒子 */
    align-items: center;
    min-height: 100vh;
    flex-direction: column;
    background: #1f2a33;
}

a {
    position: relative;
    display: inline-block;
    padding: 12px 36px;
    margin: 10px 0;
    color: #fff;
    text-decoration: none;
    text-transform: uppercase;
    font-size: 18px;
    letter-spacing: 2px;
    border-radius: 40px;
    overflow: hidden;
    background: linear-gradient(90deg, #0162c8, #55e7fc);
}
/* 子僞類選擇器 */
a:nth-child(2) {
    background: linear-gradient(90deg, #755bea, #ff72c0);
}

span {
    position: absolute;
    background: #fff;
    transform: translate(-50%, -50%);
    pointer-events: none;
    border-radius: 50%;
    animation: animate 1s linear infinite;
}

@keyframes animate {
    0% {
        width: 0px;
        height: 0px;
        opacity: 0.5;
    }
    100% {
        width: 500px;
        height: 500px;
        opacity: 0;
    }
}

JavaScript

  • 啓用 js 監聽事件
  • 定時器
  • 目的:控制動畫和單位時間內點擊效果統一
const buttons = document.querySelectorAll('a');

buttons.forEach(btn => { //箭頭函數 (ES6)

    btn.addEventListener('click', function (e) {
        let x = e.clientX - e.target.offsetLeft;
        let y = e.clientY - e.target.offsetTop;
        
        let ripples = document.createElement('span');
        
        ripples.style.left = x + 'px';
        ripples.style.top = y + 'px';
        
        this.appendChild(ripples);
        setTimeout(() => {
            ripples.remove()
        }, 1000);
    })
})

效果圖:
漣漪效果

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章