当它失去焦点时如何隐藏div? [英] How do I hide a div when it loses its focus?

查看:119
本文介绍了当它失去焦点时如何隐藏div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我正在尝试实现新Twitter的登录。当您单击登录时,会弹出包含字段的div。现在,当我点击div之外的任何地方(div失去焦点)时,div应该消失。

Basically I am trying to implement a login such as that of the new twitter. When you click on Sign In a div pops up with the fields. Now when I click anywhere outside the div (div losing focus) then the div should disappear.

我尝试了如何模糊div元素?

代码如下

$("body").click(function(evt) {

            if (evt.target.id !== 'loginDialog') {
                $("#loginDialog").hide();
            }
        });

麻烦就是target.id不等于loginDialog,即使我点击了某个地方也有了loginDialog在一个孩子里面说。

The trouble with that is the target.id will not equal to loginDialog even if I click somewhere withing loginDialog say within a child div.

所以上面是一个很好的方向,但解决方案是不完整的。

So the above is a good direction to proceed towards, but the solution is incomplete.

达到此目的的最佳方法是什么?

What is the best way to achieve this?

推荐答案

如果将鼠标移到外面是不够的,只有当用户点击它外面时你才希望它消失,这里有一个可能对你有帮助的片段。

If moving your mouse outside is not enough and you want it to disappear only if the user clicks outside of it, here's a snippet that might help you.

$('body').click(function(evt) {
    if($(evt.target).parents('#loginDialog').length==0) {
        $('#loginDialog').hide();
    }
});

这篇关于当它失去焦点时如何隐藏div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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