0

对 jquery/javascript 很陌生,但精通 html/css...

我有一个 .item 类的兄弟姐妹列表。每个都是地图上的一个大头针。我想实现三件事:

  • 单击时打开/关闭切换,使用我使用 CSS 操作的“活动”类
  • 当一个 .item 打开时,单击另一个并关闭它并打开新的
  • 在 .item 外部单击时,它将关闭

我见过一些使用 ID 的示例,但希望我可以只使用 .item 类,或者可能是父 id - #map。

我已经使用 toggleClass() 实现了第一点

$('#map .item').click(function() {
    $(this).toggleClass('active');
});

简化的html:

<div id="map">
    <div class="item"></div>
    <div class="item"></div>
    <div class="item"></div>
</div>

谢谢你的帮助。

4

2 回答 2

2

如果我正确理解,这应该有效:

$(function () {
    $('#map .item').click(function(evt) {
        evt.stopPropagation(); //stops the document click action
        $(this).siblings().removeClass('active');
        $(this).toggleClass('active');
    });


    $(document).click(function() {
        $('#map .item').removeClass('active'); //make all inactive
    });
});

您可以在此处阅读有关事件冒泡的更多信息http://api.jquery.com/event.stopPropagation/

于 2012-10-14T11:19:55.777 回答
0

像这样的东西也将起作用:

$("#map .item").click(function(e) {
    var self = $(this)[0];
    $(".item").each(function(index) {
        if (self == $(this)[0])
            $(self).addClass("active");
        else
            $(this).removeClass("active");
    });
});
$("body").click(function(e) {
    if (!e.target.id == "map" || !$(e.target).parents("#map").size()) { 
        $(".item").removeClass("active");
    }
});

这是它工作的小提琴示例。

于 2012-10-14T11:29:00.930 回答