当点击外部时,将javascript / jquery代码分解为隐藏模态

时间:2016-02-05 17:25:08

标签: javascript jquery

我有一个可行的代码,但我不知道如何分解它。看起来我能够做到这一点,因为他们基本上是相同的代码,首先是桌面型,然后是触摸设备:

//desktop

  $(document).mouseup(function (e)
  {
      var container = $(".messenger");
      if (!container.is(e.target) // if the target of the click isn't the container...
          && container.has(e.target).length === 0) // ... nor a descendant of the container
      {
          container.empty();
          container.off( 'click', clickDocument );
      }
  });



// Touch devices like IPAD and IPHONE we can use following code

$(document).on('touchstart', function (e) {
    var container = $(".messenger");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.empty();
        container.off( 'click', clickDocument );
    }
});

3 个答案:

答案 0 :(得分:2)

非常简单:

// desktop (mouseup)
// or Touch devices like IPAD and IPHONE we can use following code

  $(document).on('mouseup touchstart', function (e)
  {
      var container = $(".messenger");
      if (!container.is(e.target) // if the target of the click isn't the container...
          && container.has(e.target).length === 0) // ... nor a descendant of the container
      {
          container.empty();
          container.off( 'click', clickDocument );
      }
  });

答案 1 :(得分:2)

将其更改为:

var onMouseUp = function (e) {
    var container = $(".messenger");

    if (!container.is(e.target) // if the target of the click isn't the container...
        && container.has(e.target).length === 0) // ... nor a descendant of the container
    {
        container.empty();
        container.off( 'click', clickDocument );
    }
};

// For Desktop
$(document).mouseup(onMouseUp);

// For devices
$(document).on('touchstart', onMouseUp);

答案 2 :(得分:1)

你可以试试这个:

134566