Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
865 views
in Technique[技术] by (71.8m points)

jquery - How do I hide a div when it loses its focus?

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.

I have tried the technique mentioned at How to blur the div element?

The code is as follows

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

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

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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();
    }
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...