如何通过单击外部关闭扩展div来调用关闭事件的单击功能

时间:2016-03-07 16:26:25

标签: javascript jquery

嗯,这里有很多解决这类问题的方法。但是,我的问题是我不允许编辑现有功能。现有功能是:

$('body').on('click', '.parent.normal', function () {
  // code for Expanding a div
});

$('body').on('click', '.parent.expand', function () {
  // code for Closing expanded div
});

我可以做的是定义另一个click函数,用于在展开的div外部单击,该函数将调用现有的click事件来关闭扩展的div。为此,我写了这个:

  if($('.parent.expand').length > 0) {
    $('div:not(".parent.normal, .expanded-content, .expanded-content > div")').click(function () {
      $('.parent.expand').click();
    });
  }

实际上哪个不起作用。我怎样才能让它发挥作用?

Fiddle Demo

3 个答案:

答案 0 :(得分:1)

这将在现有功能中进行而不做任何更改

$(document).mouseup(function (e) {

   var elem_not = $(".parent.normal, .parent.expand, .expanded-content, .expanded-content > div");

   if (!elem_not.is(e.target) && elem_not.has(e.target).length === 0) {
       $('.parent.expand').click();
   }

});

更新了您的FIDDLE

答案 1 :(得分:1)

将此添加到现有代码中必须解决问题。

$(document).on('click',function(e){   
  if (!$(e.target).parents('.content').length > 0){
     $('.parent.expand').click();
  }
});

这是working Fiddle

答案 2 :(得分:0)

您需要编辑您的css,以便您的身体具有100%宽度和100%高度。这将为您的点击事件创建一个区域,以便在div之外注册。

html, body {
  margin: 0;
  padding: 0;
  height: 100%;
  width: 100%;
}

然后使用这个javascript:

// open expand content
$('body').on('click', '.parent.normal', function (e) {
  e.stopPropagation();
  e.preventDefault();
  $(this).removeClass('normal');
  $(this).addClass('expand');
  $(this).parent().find('.expanded-content').slideDown(300);
});

// close expand content
$('body').on('click', '.parent.expand', function (e) {
  e.stopPropagation();
  e.preventDefault();
  $(this).removeClass('expand');
  $(this).addClass('normal');
  $(this).parent().find('.expanded-content').slideUp(300);
});

$('body').on('click', function (e) {
  e.stopPropagation();
  e.preventDefault();
  $('.parent.expand').click();
});

Fiddle demo