如何设置jQuery加入购物车弹窗5秒后自动关闭(子主题实现)
加入购物车弹窗5秒自动关闭实现方案
问题说明
当前使用如下jQuery代码实现Add To Cart(加入购物车)弹窗功能,需要补充5秒自动关闭的超时逻辑,同时希望不修改默认jQuery代码,直接通过子主题添加该逻辑。
原有实现代码:
(function($) { "use strict"; jQuery(document).mouseup(function (e) { container = jQuery('.atc-notice-wrapper'); if (!container.is(e.target) && container.has(e.target).length === 0 ) { jQuery('.atc-notice-wrapper').fadeOut(); } }); jQuery(document).ready(function(){ jQuery('body').append('<div class="atc-notice-wrapper"><div class="atc-notice"></div><div class="close"><i class="fa fa-times-circle"></i></div></div>'); jQuery('.atc-notice-wrapper .close').on('click', function(){ jQuery('.atc-notice-wrapper').fadeOut(); jQuery('.atc-notice').html(''); }); var ajaxPId = 0; jQuery('body').on( 'adding_to_cart', function(event, button, data) { ajaxPId = button.attr('data-product_id'); }); jQuery('body').on( 'added_to_cart', function(event, fragments, cart_hash) { //get product info by ajax jQuery.post( ajaxurl, { 'action': 'get_productinfo', 'data': {'pid': ajaxPId} }, function(response){ jQuery('.atc-notice').html(response); //show product info after added jQuery('.atc-notice-wrapper').fadeIn(); } ); }); jQuery('body').on( 'added_to_cart', function(event, fragments, cart_hash) { //show product info after added jQuery('.atc-notice-wrapper').fadeIn(); }); function hideQuickView(){ jQuery('.quickview-wrapper').removeClass('open'); window.setTimeout(function(){ jQuery('body').removeClass('quickview'); }, 500); } } ); })( window.jQuery );
你预想的实现代码存在问题:当前弹窗是通过fadeIn()/fadeOut()控制显隐,并非Bootstrap模态框组件,调用.modal('hide')不会生效。
可直接用于子主题的实现代码
完全不需要修改原有默认代码,只需要把下面这段JS添加到子主题的自定义脚本中即可(可以通过主题自定义面板的自定义JS栏添加,也可以通过子主题的functions.php挂载独立JS文件):
jQuery(function($){ // 存储定时器ID,方便重复触发时重置 let atcAutoCloseTimer = null; // 弹窗自动关闭逻辑 const startAtcAutoClose = () => { // 先清除之前的定时器,避免连续加购时计时混乱 if(atcAutoCloseTimer) clearTimeout(atcAutoCloseTimer); // 400毫秒延时对应fadeIn默认动画时长,等弹窗完全显示后再开始5秒计时 atcAutoCloseTimer = setTimeout(() => { $('.atc-notice-wrapper .close').trigger('click'); }, 5400); } // 监听加购完成事件,和原有弹窗显示逻辑同步触发计时 $('body').on('added_to_cart', startAtcAutoClose); // 用户手动关闭/点击外部关闭时,清除定时器避免重复执行 $(document).on('click', '.atc-notice-wrapper .close', () => { if(atcAutoCloseTimer) clearTimeout(atcAutoCloseTimer); }); $(document).mouseup(function (e) { const container = $('.atc-notice-wrapper'); if (!container.is(e.target) && container.has(e.target).length === 0 ) { if(atcAutoCloseTimer) clearTimeout(atcAutoCloseTimer); } }); })
逻辑说明
- 复用了原有弹窗的关闭按钮触发逻辑,不需要额外写fadeOut和清空内容的代码,和原有手动关闭的行为完全一致
- 增加了定时器重置逻辑,用户连续点击加入购物车时,会重新计算5秒关闭时间,不会出现弹窗刚弹出就被关闭的问题
- 用户手动触发关闭动作时会立刻清除定时器,不会出现弹窗已经关掉了还执行无效逻辑的问题
- 额外匹配了fadeIn动画的400毫秒时长,避免动画还没播完就开始计时,导致弹窗实际显示时长不足5秒
内容的提问来源于stack exchange,提问作者user2589071
相关产品推荐
相关产品推荐

