繁体   English   中英

点击展开,外部点击折叠

[英]Expand on click, collapse on click outside

我有一个元素,我想在点击上展开,然后在外面点击折叠,从而得到以下代码。 然而,当我运行它时,它将开始扩展然后立即崩溃,因为两个函数都是按顺序调用的。 我不明白为什么以及如何解决这个问题。

jQuery(document).ready(function() {

var element         = jQuery("#search-main");
var defaultWidth    = jQuery("#search-main").css('width');
var expandWidth     = "200px";

var fnSearch = {
    expand : function() {

        jQuery(element).animate({
            width : expandWidth
        });

        jQuery(document).bind('click', fnSearch.collapse);
    },

    collapse : function() {

        jQuery(element).animate({
            width : defaultWidth
        });

        event.stopPropagation();

        jQuery(document).unbind("click", fnSearch.collapse);

    }
}

jQuery("#search-main").bind("click", fnSearch.expand);

});

您遇到了问题,因为#search-main click事件正在传播到文档; 即首先触发#search-main click事件,然后触发document点击事件。 Click事件默认执行此操作。 要停止此事件传播,您需要在expand功能中使用http://api.jquery.com/event.stoppropagation/

jQuery(document).ready(function() {

var element         = jQuery("#search-main");
var defaultWidth    = jQuery("#search-main").css('width');
var expandWidth     = "200px";

var fnSearch = {
    expand : function(event) { // add event parameter to function
        // add this call:
        event.stopPropagation();

        jQuery(element).animate({
            width : expandWidth
        });

        jQuery(document).bind('click', fnSearch.collapse);
    },

    collapse : function() {

        jQuery(element).animate({
            width : defaultWidth
        });

        jQuery(document).unbind("click", fnSearch.collapse);

    }
}

jQuery("#search-main").bind("click", fnSearch.expand);

});

也就是说,Jason P的解决方案更适合您的需求。 它更可靠,更简洁,因为您不必将document绑定到document ,如果您习惯性地使用该策略,这很容易变得难以跟踪并导致与其他代码冲突。

单击后可以从#search-main元素取消绑定click事件,或者停止事件的传播,但我建议绑定到blur和focus事件:

http://jsfiddle.net/6Mxt9/

(function ($) {
    $(document).ready(function () {
        var element = jQuery("#search-main");
        var defaultWidth = jQuery("#search-main").css('width');
        var expandWidth = "200px";

        $('#search-main').on('focus', function () {
            $(element).animate({
                width: expandWidth
            });
        }).on('blur', function () {
            $(element).animate({
                width: defaultWidth
            });
        });
    });
})(jQuery);

这样,即使用户选择进入或离开字段,它也会起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM