1

考虑以下代码

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;
            }        
        }
    });
});

正如您在此处看到的,会发生某种闪烁,因为当.b显示时,mouseout会自动发生。你将如何解决这个问题?

期望的行为是:当鼠标悬停时.a.b应该显示(应该覆盖.a),当鼠标未悬停时.a.b不应该显示。.a应始终显示。

的位置和尺寸.a不是恒定的(应即时计算)。

4

2 回答 2

3

我想出了这个解决方案

$(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();
    });
});
于 2010-09-16T07:02:26.287 回答
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。

于 2010-09-16T07:03:22.120 回答