3

我有一个<ul>,当点击时,切换另一个的可见性<ul>。当显示 s 时,如何将事件附加到页面的正文,<ul>以便正文将隐藏<ul>.

我是新来写这些冒泡的东西,我不明白为什么我到目前为止所做的似乎间歇性地工作。多次点击,打开open次要添加类失败<ul>

当然,可能有更好的方法来做到这一点。

$(document).on('click', '.dd_deploy', function (e) {
    var ul = $(this).children('ul');
    var height = ul.css('height');
    var width = ul.css('width');
    ul.css('top', "-" + height);
    ul.fadeToggle(50, function () {

        //add open class depending on what's toggled to
        if (ul.hasClass('open')) {
            ul.removeClass('open');
        } else {
            ul.addClass('open');
        }
        //attach click event to the body to hide the ul when
        //body is clickd
        $(document).on('click.ddClick', ('*'), function (e) {
            e.stopPropagation();
           //if (ul.hasClass('open')) {
                ul.hide();
                ul.removeClass('open')
                $(document).off('click.ddClick');
           // }
        });
    });
});​

http://jsfiddle.net/JYVwR/

4

2 回答 2

2

我建议不要在点击事件中绑定点击事件,即使您正在取消绑定它。相反,我会这样做:

http://jsfiddle.net/JYVwR/2/

$(document).on('click', function (e) {
    if ( $(e.target).is(".dd_deploy") ) {
        var ul = $(e.target).children('ul');
        var height = ul.css('height');
        var width = ul.css('width');
        ul.css('top', "-" + height);
        ul.fadeToggle(50, function () {

            //add open class depending on what's toggled to
            if (ul.hasClass('open')) {
                ul.removeClass('open');
            } else {
                ul.addClass('open');
            }
        });
    }
    else {
        $('.dd_deploy').children('ul:visible').fadeOut(50,function(){
            $(this).removeClass("open");
        })
    }
});​

If you need to further prevent clicking on the opened menu from closing the menu, add an else if that tests for children of that menu.

于 2012-12-21T20:20:46.970 回答
-1

You dont' really need all that code. All you need is jquery's toggle class to accomplish what you want. simple code like one below should work.

Example Code

$(document).ready(function() {
    $('ul.dd_deploy').click(function(){
        $('ul.dd').toggle();
    });
});​​​​

Firstly, you are defining a document.on function within a document.on function which is fundamentally wrong, you just need to check it once and execute the function once the document is ready.

Secondly why do you want to bind an event to body.click ? it's not really a good idea.

Suggestion

I think you should also look at the hover function which might be useful to you in this case.

Working Fiddles

JSfiddle with click function JSfiddle with hover function

于 2012-12-21T20:26:09.123 回答