需要帮助Javascript“mouseover”和“mouseout”事件

时间:2010-09-16 06:37:15

标签: javascript jquery javascript-events mouseover mouseout

考虑the following code

HTML:

<div class='a'></div>
<div class='b'></div>

CSS:

body {
    position: relative;
}
.a {
    position: absolute;
    left: 100px;
    top: 100px;
    width: 100px;
    height: 100px;
    background: #777;
}
.b {
    position: absolute;
    display: none;
    background: red;
}

JavaScript的:

$(function() {
    $('.a').live('mouseover mouseout', function(e) {
        switch (e.type) {
            case 'mouseover': {
                $('.b').offset({'left': $(this).offset().left,
                                'top': $(this).offset().top})
                       .width($(this).outerWidth())
                       .height($(this).outerHeight())
                       .show();
                break;
            }       
            case 'mouseout': {
                $('.b').hide();
                break;
            }        
        }
    });
});

正如您所见here,会发生某种闪烁,因为当显示.b时,mouseout会自动发生。你会如何解决这个问题?

所需的行为是:当鼠标结束.a时,应显示.b(应覆盖.a),当鼠标未超过.a时,不应显示.b。应始终显示.a

.a的位置和尺寸不是恒定的(应该在运行中计算)。

2 个答案:

答案 0 :(得分:3)

我提出了this solution

$(function() {
    $('.a').live('mouseover', function(e) {
        $('.b').offset({'left': $(this).offset().left,
                        'top': $(this).offset().top})
               .width($(this).outerWidth())
               .height($(this).outerHeight())
               .show();
    });
    $('.b').live('mouseout', function(e) {
        $(this).hide();
    });
});

答案 1 :(得分:0)

尝试

$(function() {
    $('.a').live('mouseover', function(e) {
        $('.b').offset({'left': $(this).offset().left,
                        'top': $(this).offset().top})
                .width($(this).outerWidth())
                .height($(this).outerHeight())
                .show();
    });
    $('.b').live('mouseout', function(e) {
        $('.b').hide();
        break;
    });
});

这意味着当用户将鼠标移动到区域a上时,会显示区域b,然后当他们将鼠标移出区域b时,区域a将被重新显示。