【问题标题】:Javascript "mouseover" and "mouseout" eventsJavascript“mouseover”和“mouseout”事件
【发布时间】:2011-04-13 01:27:58
【问题描述】:

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

【问题讨论】:

  • 最初应该.b 覆盖 .a吗?
  • 没有。仅当鼠标悬停在.a上时。
  • 你可以尝试让.b 成为.a 的孩子,尽管有时这可能并不理想
  • 您是否尝试过添加几毫秒的计时器,以便它可以触发鼠标悬停事件并保持显示?
  • 我不喜欢超时的想法。我正在寻找更清洁的解决方案。

标签: javascript jquery mouseover jquery-events mouseout


【解决方案1】:

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

【讨论】:

  • 设置位置时将$('.b').offset改为$('.b').css。否则这行得通。
【解决方案2】:

试试

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

【讨论】:

  • 这正是我想出的解决方案:) 但不是,我认为这还不够好,因为.b 的尺寸可能与.a 的尺寸不同。你有什么别的想法吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-01-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-07-29
  • 2017-04-12
相关资源
最近更新 更多