开发者

jQuery problem within clicking on page

Ok, I am using this jQuery here:

$('html').click(function(){
    if ($(".trigger").hasClass("active"))
    {
        $(".panel").toggle("fast");
        $(this).toggleClass("active");
    }
});

$(".panel").click(function(event){
    event.stopPropagation();
});

$(document).ready(function(){
    $(".trigger").click(function(){
    $(".panel").toggle("fast");
    $(this).toggleClass("active");
    return false;
    });
});

Ok, so a reply stated that I should visit another answer, have tried this, but this only works on the first try. If I show click on the trigger again after that than click on anywhere in the page, it doesn't work again. It fails to hide it all of the time when it is visible. How can I fix this?

So, when the panel gets displayed, I'd like to be able to click outside of the panel to hide it again for everytime that it gets displayed. I would like to have the opportun开发者_JAVA百科ity to ONLY be able to click on the class="trigger" object in order to display and hide the class="panel" object by either clicking on the class="trigger" object again, or clicking outside of the class="panel" object anywhere on the page.

How can I do this?


$('.panel').hide();

$(document).click(function(e){
    var $t = $(e.target);
    if($t.is('.trigger *,.trigger')){
        $(".panel").toggle("fast");
        $t.closest('.trigger').toggleClass("active");
    } else if(!$t.is('.panel *,.panel')){
        $(".panel").hide("fast");
        $('.trigger.active').removeClass("active");
    }
});

check out here: http://jsfiddle.net/5fU3v/2/


You can stop event propagation in the click handler you register on the trigger, then register another click handler on the html element and use the :visible selector to determine if the panel is hidden or not:

$(document).ready(function() {
    $(".trigger").click(function(e) {
        e.stopPropagation();
        e.preventDefault();
        $(".panel").toggle("fast");
        $(this).toggleClass("active");
    });

    $("html").click(function() {
        var $panel = $(".panel:visible");
        if ($panel.length) {
            $panel.hide("fast");
            $(".trigger").removeClass("active");
        }
    });
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜