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

如何在TailwindCSS中实现鼠标悬停触发的涟漪效果?

在Tailwind CSS中实现悬停触发的涟漪效果

核心思路

点击触发的涟漪逻辑是监听click事件,悬停触发只需将事件替换为mouseenter,同时调整涟漪元素的动画逻辑——从鼠标悬停位置向外展开,动画结束后自动清理元素。核心依然是在目标容器内动态创建涟漪元素,结合Tailwind样式控制定位、尺寸与动画效果。

完整实现示例

1. HTML结构

需要一个相对定位的容器(按钮、卡片等均可),确保涟漪在其边界内展示:

<button class="relative overflow-hidden px-8 py-3 bg-blue-600 text-white rounded-lg cursor-pointer hover:bg-blue-700 transition-colors">
  悬停触发涟漪
</button>
  • relative:让内部绝对定位的涟漪元素以该容器为基准
  • overflow-hidden:裁剪超出容器的涟漪部分,保证效果边界清晰

2. JavaScript逻辑

监听mouseenter事件,计算鼠标在容器内的坐标,创建并挂载涟漪元素,动画结束后自动移除:

// 获取所有需要添加涟漪效果的目标元素
const rippleTargets = document.querySelectorAll('.relative.overflow-hidden');

rippleTargets.forEach(target => {
  target.addEventListener('mouseenter', (e) => {
    // 创建涟漪元素
    const ripple = document.createElement('span');
    
    // 获取容器尺寸与鼠标在容器内的相对位置
    const rect = target.getBoundingClientRect();
    const rippleSize = Math.max(rect.width, rect.height);
    const posX = e.clientX - rect.left - rippleSize / 2;
    const posY = e.clientY - rect.top - rippleSize / 2;
    
    // 给涟漪元素添加Tailwind样式
    ripple.classList.add(
      'absolute',
      'rounded-full',
      'bg-white/30', // 可自定义颜色与透明度,比如bg-gray-200/40
      'animate-ripple',
      'pointer-events-none' // 避免涟漪元素干扰鼠标事件
    );
    
    // 设置涟漪的初始尺寸与位置
    ripple.style.width = `${rippleSize}px`;
    ripple.style.height = `${rippleSize}px`;
    ripple.style.left = `${posX}px`;
    ripple.style.top = `${posY}px`;
    
    // 将涟漪元素添加到目标容器中
    target.appendChild(ripple);
    
    // 动画结束后移除涟漪元素,避免DOM冗余
    ripple.addEventListener('animationend', () => ripple.remove());
  });
});

3. 自定义涟漪动画

两种方式实现动画效果,选其一即可:

方式一:修改Tailwind配置文件

在tailwind.config.js中扩展动画规则:

/** @type {import('tailwindcss').Config} */
module.exports = {
  content: ["./src/**/*.{html,js}"],
  theme: {
    extend: {
      animation: {
        'ripple': 'ripple 0.6s ease-out forwards',
      },
      keyframes: {
        ripple: {
          '0%': { transform: 'scale(0)', opacity: 1 },
          '100%': { transform: 'scale(4)', opacity: 0 },
        },
      },
    },
  },
  plugins: [],
}

方式二:直接添加自定义CSS

无需修改Tailwind配置,在全局CSS中添加动画:

@tailwind base;
@tailwind components;
@tailwind utilities;

@keyframes ripple {
  0% { transform: scale(0); opacity: 1; }
  100% { transform: scale(4); opacity: 0; }
}

.animate-ripple {
  animation: ripple 0.6s ease-out forwards;
}

效果调整说明

  • 涟漪颜色:修改bg-white/30中的颜色值与透明度,比如bg-purple-500/20
  • 动画速度:调整动画时长(如0.6s改为0.8s)
  • 展开范围:修改scale(4)中的数值,数值越大涟漪展开范围越广

内容的提问来源于stack exchange,提问作者Big boy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 05:18:33