单击任何位置,但在元素上隐藏它与if语句 [英] Click anywhere but on the element to hide it w/ if-statement

查看:134
本文介绍了单击任何位置,但在元素上隐藏它与if语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下解决方案

我已经阅读了有关此概念的大多数问题,但我似乎无法理解使用if语句。有什么帮助?

I've read through most questions around here concerning this concept, but I can't seem to get it to work with an if-statement. Any help?

JSFiddle

$("button").click(function () {
  $("div").fadeToggle("fast");
});

if ($("div").is(":visible")) {
  $(document).click(function () {
    $("div").fadeToggle("fast");
  });

  $("div").click(function (e) {
    e.stopPropagation();
  });
}

因此,按钮应该切换div。当切换div时(即:visible ),只能通过单击页面上的任何位置来切换回(不可见)div,而不是在单击div本身时切换。

So, the button should toggle the div. When the div is toggled (i.e. :visible) the div should only be toggled back (not visible) by clicking anywhere on the page, but not when clicking on the div itself.

我合并 Diabolic的答案 Kevin Bowersox的答案进入这一个

$("button").click(function (e) {
    $("div").fadeToggle("fast");
    e.stopImmediatePropagation();
});

$(document).click(function (e) {
    if($("div").is(":visible") && !$("div").is(e.target)) {
        $("div").fadeOut("fast");
    }
});


推荐答案

Javascript

$("button").click(function (e) {
  $("div").fadeToggle("fast");
});

$(document).mouseup(function(event){
    var target = $("#no-mod");
    if(!target.is(event.target) && !$("button").is(event.target) && target.is(":visible")){
       $("div").fadeToggle("fast");
    }else{
      return false;
    }
});

HTML

<button>Click me</button>
<div id="no-mod"></div>

示例: http://jsfiddle.net/2udYp/9/

这篇关于单击任何位置,但在元素上隐藏它与if语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆