You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将按钮的Ripple(涟漪)效果限制在按钮范围内

解决涟漪效果超出按钮范围的问题

问题根源

  1. 定位上下文错误:你的按钮默认是position: static(浏览器默认值),而涟漪元素用了position: absolute。绝对定位元素会相对于最近的非static定位父元素布局,所以当前涟漪是相对于<body>定位的,按钮的overflow: hidden无法限制它的显示范围。
  2. 位置计算错误:e.clientY/e.clientX是相对于浏览器视口的坐标,没有考虑按钮本身在页面中的偏移,导致涟漪位置和点击位置不匹配,也会加剧溢出问题。

修复步骤

  1. 给按钮添加position: relative,让涟漪的绝对定位以按钮为上下文。
  2. 改用e.offsetY/e.offsetX计算涟漪位置,这两个值是相对于按钮内部的坐标,能精准定位到点击点中心。

修改后的完整代码

JavaScript

document.getElementById("btn").addEventListener("mousedown",(e)=>{
  const btn = e.currentTarget;
  const ripple = document.createElement("span")
  ripple.classList.add("ripple")
  btn.appendChild(ripple)
  ripple.style.animation = "ripple 500ms linear forwards"
  // 涟漪宽高50px,所以减去25px让中心对准点击点
  ripple.style.top = `${e.offsetY - 25}px`;
  ripple.style.left = `${e.offsetX - 25}px`;
  setTimeout(()=>{
    ripple.remove()
  },500)
})

CSS

.modaljs-btn-green {
    position: relative; /* 开启相对定位,作为涟漪的定位容器 */
    padding: 10px;
    font-size: 15px;
    color: #28b32f;
    font-weight: 600;
    border: none;
    outline: none;
    border-radius: 2px;
    transition: all 325ms;
    cursor: pointer;
    margin-left: 10px;
    overflow: hidden;
}
.modaljs-btn-green:hover {
    background-color: rgb(198, 255, 196);
}

.ripple{
    border-radius: 50%;
    position: absolute;
    background-color: grey;
    width: 50px;
    height: 50px;
    opacity: 0.5;
}

@keyframes ripple{
    0%{
        transform: scale(0);
        opacity: 0.5;
    }
    100%{
        transform: scale(3);
        opacity: 0;
    }
}

HTML

<button id="btn" class="modaljs-btn-green">LOGIN</button>

内容的提问来源于stack exchange,提问作者Shlok Jain

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 22:20:38