结合js实现按钮点击水波纹效果

2,655 阅读1分钟

效果图

实现原理

利用js获取鼠标相对按钮的位置,并设置给波纹小球。利用scale()加css动画来实现波纹小球的扩展。

实现步骤

1、预设小球样式与动画效果

2、监听按钮点击事件,获取鼠标相对按钮位置

3、创建dom节点

4、为dom节点添加相应类与初始位置的样式

5、监听动画结束事件,移除小球

代码实现

css部分

#button {
    position: relative;
    display: block;
    margin: 200px auto;
    width: 200px;
    height: 50px;
    text-align: center;
    line-height: 50px;
    transform: translateY(-50%);
    /* 伪类会扩张,最后溢出按钮框,
    所以需要设置overflow:hidden隐藏 */
    overflow: hidden;
    border: 1px solid rgba(0,0,0,.4);
    user-select:none;
}
#button:hover {
    background: rgba(0,0,0,.4);
}

/* 实现水波纹效果的小球样式 */
#button > .ripple-ball {
    position: absolute;
    display: block;
    width: 20px;
    height: 20px;
    border-radius: 50%;
    background: rgba(0,0,0,.4);
    animation: ripple 1s;	
}
/* 小球动画 */
@keyframes ripple {
    0% {
        transform: scale(2);
    } 
    /* 波纹扩张 */
    85% {
        transform: scale(25);
    }
    100% {
        opacity: 0
    }
}

html部分

<div id="button">
    <p>button</p>
</div>

js部分

const btn = document.getElementById('button');

btn.onclick = (event) => {
    // 创建波纹小球dom
    const rippleBall = document.createElement('span')
    
    // 获取波纹小球dom初始位置
    const x = event.clientX - btn.getBoundingClientRect().x - 10
    const y = event.clientY - btn.getBoundingClientRect().y - 10
    
    // 波纹小球样式设置
    rippleBall.style.left = x + 'px'
    rippleBall.style.top = y + 'px'
    rippleBall.classList.add('ripple-ball')
    
    // 波纹小球挂载
    btn.appendChild(rippleBall)
    
    // 监听动画结束事件,以移除小球
    rippleBall.addEventListener('animationend', () => {
        btn.removeChild(rippleBall)
    })
}