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

如何用jQuery data属性实现鼠标离开时触发指定弹窗(附现有代码)

实现基于data属性的鼠标离开触发弹窗功能

嘿,我来帮你搞定这个需求!你的现有代码已经通过data属性实现了点击打开/关闭弹窗的功能,现在要扩展成鼠标离开时触发指定弹窗的操作,完全可以沿用这套data属性机制,只需要在initPopup()函数里新增针对mouseleave事件的处理逻辑就行。

修改后的完整代码

function initPopup() {
    // ----- OPEN 点击打开弹窗
    $('[data-popup-open]').on('click', function (e) {
        var targeted_popup_class = jQuery(this).attr('data-popup-open');
        $('[data-popup="' + targeted_popup_class + '"]').fadeIn(350);
        e.preventDefault();
    });

    // ----- CLOSE 点击关闭弹窗
    $('[data-popup-close]').on('click', function (e) {
        var targeted_popup_class = jQuery(this).attr('data-popup-close');
        $('[data-popup="' + targeted_popup_class + '"]').fadeOut(350);
        e.preventDefault();
    });

    // ----- TRIGGER ON MOUSE LEAVE 鼠标离开触发弹窗操作
    $('[data-popup-leave]').on('mouseleave', function (e) {
        var targeted_popup_class = jQuery(this).attr('data-popup-leave');
        // 这里默认是关闭弹窗,若需要打开弹窗,把fadeOut改成fadeIn即可
        $('[data-popup="' + targeted_popup_class + '"]').fadeOut(350);
        e.preventDefault();
    });
}

$(document).ready(function () {
    initPopup();
});

使用说明

  • 如果你想让鼠标离开某个元素时关闭指定弹窗,给该元素添加属性:data-popup-leave="你的弹窗标识",示例代码如下:
    <div data-popup-leave="login-popup">鼠标离开我就关闭登录弹窗</div>
    <div data-popup="login-popup" style="display:none;">这是登录弹窗</div>
    
  • 如果需要鼠标离开时打开弹窗,只需要把代码中mouseleave事件里的fadeOut(350)替换成fadeIn(350)就可以了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 10:02:50