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

如何在窗口失焦时暂停jQuery Ripples动画?

解决jQuery Ripples窗口失焦时动画累积的问题

问题分析

你的代码存在几个关键问题导致功能失效:

  • 重复的$(document).one('click')事件绑定,只会执行第一个,逻辑矛盾
  • 水滴触发的setInterval没有判断窗口焦点状态,失焦时仍在持续生成水滴,导致返回后一次性触发所有累积的水滴
  • 代码末尾多余的});造成语法错误
  • 未正确关联窗口焦点事件与ripples的播放状态控制

修正后的完整代码

<script src="https://cdn.jsdelivr.net/npm/jquery.ripples@0.6.3/dist/jquery.ripples.min.js"></script>
<script>
$(document).ready(function() {
    // 初始化ripples效果
    $('#ripple').ripples({
        resolution: 512,
        dropRadius: 30,
        perturbance: 0.04,
    });

    let dropInterval; // 保存水滴定时器ID

    // 生成水滴的函数
    function createRandomDrop() {
        const $el = $('#ripple');
        const x = Math.random() * $el.outerWidth();
        const y = Math.random() * $el.outerHeight();
        const dropRadius = 30;
        const strength = 0.04 + Math.random() * 0.04;
        $el.ripples('drop', x, y, dropRadius, strength);
    }

    // 启动水滴定时器
    function startDropInterval() {
        dropInterval = setInterval(createRandomDrop, 2500);
    }

    // 停止水滴定时器
    function stopDropInterval() {
        if (dropInterval) {
            clearInterval(dropInterval);
            dropInterval = null;
        }
    }

    // 窗口聚焦时恢复动画和水滴生成
    $(window).on('focus', function() {
        $('#ripple').ripples('play');
        startDropInterval();
    });

    // 窗口失焦时暂停动画并停止水滴生成
    $(window).on('blur', function() {
        $('#ripple').ripples('pause');
        stopDropInterval();
    });

    // 初始状态:页面加载后自动启动(或保留点击触发,根据需求调整)
    startDropInterval();

    // 如果你需要点击页面才启动,替换上面的startDropInterval()为下面的代码:
    // $(document).one('click', function() {
    //     $('#ripple').ripples('play');
    //     startDropInterval();
    // });
});
</script>

关键说明

  1. 定时器管理:用变量dropInterval保存定时器ID,失焦时通过clearInterval彻底停止水滴生成,避免累积
  2. 焦点事件绑定:通过window的focus和blur事件,分别控制ripples的播放/暂停,以及水滴定时器的启停
  3. 语法修正:将所有代码包裹在$(document).ready()中,确保DOM元素加载完成后再初始化ripples,同时移除多余的语法错误代码
  4. 逻辑优化:将水滴生成逻辑封装为函数,便于复用和维护,避免重复代码

这样修改后,切换标签页时:

  • 窗口失焦:立即暂停ripples动画,停止生成新的水滴
  • 窗口聚焦:恢复ripples动画,重新开始定时生成水滴,不会出现累积的一次性触发问题

内容的提问来源于stack exchange,提问作者Eduardo Lacayo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 00:15:59