单击空白区域返回选定的部分

时间:2013-03-29 09:53:04

标签: javascript jquery

<li class="list "><a href="javascript:">A</a>

    <ul class="names">
        <li class="list"><a href="javascript:">1</a>
        </li>
        <li class="list"><a href="javascript:">2</a>
        </li>
    </ul>
</li>
<li class="list "><a href="javascript:">B</a>

    <ul class="names selected">
        <li class="list selected"><a href="javascript:">1</a>
        </li>
        <li class="list"><a href="javascript:">2</a>
        </li>
        <li class="list"><a href="javascript:">3</a>
        </li>
        <li class="list"><a href="javascript:">4</a>
        </li>
    </ul>
</li>
<li class="list "><a href="javascript:">C</a>

    <ul class="names">
        <li class="list"><a href="javascript:">1</a>
        </li>
        <li class="list"><a href="javascript:">2</a>
        </li>
        <li class="list"><a href="javascript:">3</a>
        </li>
        <li class="list"><a href="javascript:">4</a>
        </li>
    </ul>
</li>

    $('.list').click(function () {
        var that = this;
        $('.list').each(function () {
            if (that == this) return true; //continue
            $('.names:not(:hidden)', this).slideToggle();
        });
        $('ul.names', this).slideToggle();
    })
ul.names{display: none;}
li.list{
    width:150px;
       background:#A9FF7A;
}
ul.names {
    width:150px;
    background:#A9FF7A;
}
ul.selected{
    display: block;
}
li.selected{
    background:red;
}

在线示例:http://jsfiddle.net/gyYyd/

突出显示

B 的子菜单 1 。如果我单击菜单A或C,则会打开A或C部分,但如何单击PAGE BLANK区域(背景颜色之外)返回B部分(打开B部分)

提前致谢

1 个答案:

答案 0 :(得分:1)

您可以在click对象上捕获document,并在所需的列表项上触发click

$(document).click(function() {
    var selected = $('.selected:first');
    if(!selected.closest('ul.names').is(':visible')) {
        selected.closest('.list').trigger('click');
    }
});

此外,请确保从当前列表项return false处理程序中click - 以便列表项的正常点击不会传播到上述处理程序。

DEMO http://jsfiddle.net/gyYyd/2/