繁体   English   中英

Javascript“mouseover”和“mouseout”事件

[英]Javascript “mouseover” and “mouseout” events

考虑以下代码

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的位置和尺寸不是恒定的(应该即时计算)。

我想出了这个解决方案

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

试试

$(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。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM