定位绝对div并在div之外切换

时间:2011-08-22 09:58:04

标签: javascript jquery html css

<div id="menu">
    HERE
</div>

<div id="menu2">
    <span id="one" class="menu2">1. one </span>
    <span id="two" class="menu2">2. two </span>
</div>

#menu {
background-color: red;
width: 100px;
height: 100px
}
#menu2 {
    display: none;
    background-color: green;
    position: absolute;
}


$('#menu').live('click', function(e) {
    $('#menu2').toggle();
});

$('.menu2').live('click', function(e) {
    $('#menu').html($(this).attr('id'));
});

我如何设置.menu2在哪里点击? 如果我点击#menu外面怎么能隐藏#menu2?如果我点击了.menu2

直播示例:http://jsfiddle.net/FhVgp/

1 个答案:

答案 0 :(得分:3)

jsFiddle demo

$('#menu').bind('click', function(e) {
    e.stopPropagation();
    var posX = e.pageX;
    var posY = e.pageY;

    $('#menu2').toggle().css({left: posX, top: posY });
});

$('.menu2').live('click', function(e) {
    $('#menu').html($(this).attr('id'));
});

$(document).bind('click', function() {
    if ($('#menu2').is(':visible')) {
        $("#menu2").hide();
    }
});