jQuery - fade out when clicking on parent element (and not the parents children)?

妖精的绣舞 提交于 2019-12-21 20:22:05

问题


I've got the following code on my page, and what i'm trying to do is that when a user clicks outside the #loginBox, i want the entire #loginOverlay to fadeout. But i can't achieve this effect without having the fadeout triggered by clicking on #loginBox...

It's placed on the bottom of the page, and i have a link on the page that triggers the fadein. But the fadeout is a bit struggling now tbh.

I tried doing this:

$("#loginOverlay").click(function() { ...fadeout... });

but it gives me the same result.

So any suggestions? Thanks in advance!

<div id="loginOverlay">
    <div id="loginBox">
        <img class="closeBtn" src="images/icons/close.png" alt="" />
        <h3>Login</h3>
        <form action="login.php?ref=index.php" method="post">
            <input type="text" name="username" value="Username..." onblur="if(this.value.length == 0) this.value='Username...';" onclick="if(this.value == 'Username...') this.value='';" />
            <input type="password" name="password" value="Password..." onblur="if(this.value.length == 0) this.value='Password...';" onclick="if(this.value == 'Password...') this.value='';" />
            <input class="loginBtn" type="submit" name="submit" value="Login!" />
        </form>
    </div> <!--login box -->
</div>



<script src="js/jquery-1.4.2.min.js"></script>
<script>
$(document).ready(function() {
    $('#loginOverlay').css('display', 'none');

    $('#loginToggle').click(function() {
        $("#loginOverlay").fadeIn(200);
    });

    $("#loginBox").parent().click(function(){
        $("#loginOverlay").fadeOut(100);
    });

});

回答1:


You need to check e.target to see what element was actually clicked:

$("#loginOverlay").click(function(e) {
    if (e.target === this)
        $("#loginOverlay").fadeOut(100);
});


来源:https://stackoverflow.com/questions/2765447/jquery-fade-out-when-clicking-on-parent-element-and-not-the-parents-children

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!