【问题标题】:Toggling between hide and show and hiding div on mouse up在鼠标上移时在隐藏和显示和隐藏 div 之间切换
【发布时间】:2014-01-04 06:01:03
【问题描述】:

我有一个登录链接,点击它会显示一个 div。单击链接时,我想在该 div 的隐藏和显示之间切换。此外,一旦用户在 div 之外单击,我还需要隐藏 div。

我所做的如下所示:

$(document).ready(function() {
    $("#poplink").click(function() {
        $('#popup').toggle();
    });
    $(document).mouseup(function(e) {
        var container = $("#popup");
        if (!container.is(e.target) && container.has(e.target).length === 0) { // if the target of the click isn't the container...
            // ... nor a descendant of the container
            container.hide();
        }
    });
});

现在的问题是我无法在隐藏和显示之间切换。当我在 div 外部单击时,它完美地隐藏了。

谁能帮我解决这个问题。 FIDDLE

【问题讨论】:

  • 你可能想看看这个jqueryui.com/dialog/#modal-form
  • $('#regpopup').hide(); 好像没用过,所以多余
  • @dan 我相信 OP 只是没有复制 #regpopup 的代码。
  • 我有其他具有相同属性的 div regpopup。所以我没有复制它的代码。很抱歉这个错误。

标签: jquery html toggle


【解决方案1】:

为文档注册一个点击处理程序而不是 mouseup

$(document).ready(function () {
    $("#poplink").click(function (e) {
        e.stopPropagation();
        $('#popup').toggle();
        $('#regpopup').hide();
    });

    $(document).click(function (e) {
        var container = $("#popup");
        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.hide();
        }
    });

});

演示:Fiddle

【讨论】:

  • 非常感谢您的想法。我希望所有浏览器的行为都是一致的。
【解决方案2】:

嗯,我知道你在哪里复制了那段内容。为您更改了它,现在它可以工作了:

$(document).ready(function()
{
  $("#poplink").click(function(e)
  {
    e.stopPropagation();
    $('#popup').toggle();
    $('#regpopup').hide();
  });
  $("*:not(#poplink)").click(function (e) {
    var container = $("#popup");
    if (!container.is(e.target) && container.has(e.target).length === 0)
    {
      container.hide();
    }
  });
});

还有 JSFiddle:http://jsfiddle.net/f9Ywh/8/

【讨论】:

  • 我想在单击链接时在 div 的隐藏/显示之间切换。那是我没有得到的。
  • 嗯,很有用。太棒了!
猜你喜欢
  • 1970-01-01
  • 2013-01-16
  • 1970-01-01
  • 2011-11-08
  • 2016-08-26
  • 1970-01-01
  • 2015-02-23
  • 2023-03-20
  • 1970-01-01
相关资源
最近更新 更多