Javascript "mouseover"和 "mouseout"事件

标签 javascript jquery mouseover jquery-events 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 的位置和尺寸不是常量(应即时计算)。

最佳答案

我想出了 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();
    });
});

关于Javascript "mouseover"和 "mouseout"事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3724249/

相关文章:

jquery - 根据 jQuery 中的片段 ID 采取行动

wpf 鼠标悬停填充矩形

当实际网页打开时,HTML 链接不起作用,仅当我从 Dreamweaver 测试它到浏览器时才起作用

JavaScript:防止无意中创建新属性

javascript - 显示/隐藏单个 Div 的简便方法?

javascript - 如何将所有像素大小的图像放入一个 div 中?

javascript - 我正在尝试使用 jquery 启用下拉菜单

html - Firefox 和 IE8 不显示图像映射的鼠标悬停替代文本的问题

javascript - 在不指定纬度和经度的情况下将谷歌地图置于地点 ID 的中心?

javascript - 有没有一种简单的方法可以通过相应的 img hover jquery 来定位这些 h2 中的每一个