【问题标题】:Issue hiding div with 'event.stopPropagation'使用“event.stopPropagation”隐藏 div
【发布时间】:2017-07-16 23:43:18
【问题描述】:

使用 Cart.JS 为 Shopify 开发 Ajax 购物车。

我用于隐藏显示“ajaxcart”容器的原始代码:

<script>
  $(document).ready(function(){
    $("lightbox").hide();
    $("ajaxcart").hide();
    $('#button').click(function(event){
        $('lightbox').show().addClass('fadeIn').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', 
        function() {
          $(this).removeClass('fadeIn');
        });
        $('ajaxcart').show().addClass('slideInRight').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', 
        function() {
          $(this).removeClass('slideInRight');
        });
            event.stopPropagation();
    });
    $("#button").on("click", function (event) {
        event.stopPropagation();
    });
    $('html').click(function() {
      $('lightbox').show().addClass('fadeOut').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', 
        function() {
          $(this).removeClass('fadeOut');
            $(this).hide();
        });
        $('ajaxcart').show().addClass('slideOutRight').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', 
        function() {
          $(this).removeClass('slideOutRight');
          $(this).hide();
        });
    });

    $('ajaxcart').click(function(event){
        event.stopPropagation();
    }); 
});
</script>

但是,当使用 event.stopPropagation(); 的隐藏部分时,由于停止事件,它会弄乱使用购物车按钮的代码。

我创建了一个实时测试,因此您可以看到购物车中的按钮没有响应:https://eldecosmetics.com/pages/bergen

任何想法如何安全地隐藏“ajaxcart”容器而不停止容器和 Ajax 中的事件,并且不使用 event.stopPropagation(); 的最后一部分,这似乎是问题所在?

【问题讨论】:

  • 假设 'ajaxcart' 是一个自定义元素,您可以使用 jQuery hide 方法隐藏该元素。 event.stopPropagation();不隐藏元素。 $('ajaxcart').click(function(event) { $(this).hide(); });
  • @RajeshP 我知道,但这并不能让我仅在单击“ajaxcart”外部时才能关闭“ajaxcart”。如果我删除 event.stopPropagation() 'ajaxcart' 在单击容器时也会关闭。

标签: javascript jquery ajax shopify


【解决方案1】:

在“ajaxcart”外部单击时,而不是使用$('html').click(function() 来隐藏 div。我创建了一个新的 div 位置:absolute;填充“ajaxcart”后面的整个身体区域。然后用它来关闭'ajaxcart'。

$('lightbox').click(function() {
      $('lightbox').show().addClass('fadeOut').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', 
        function() {
          $(this).removeClass('fadeOut');
            $(this).hide();
        });
        $('ajaxcart').show().addClass('slideOutRight').one('webkitAnimationEnd mozAnimationEnd MSAnimationEnd oanimationend animationend', 
        function() {
          $(this).removeClass('slideOutRight');
          $(this).hide();
        });
    });

【讨论】:

    猜你喜欢
    • 2022-01-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多