【问题标题】:jquery two divs using 'hover' eventjquery 使用“悬停”事件的两个 div
【发布时间】:2011-11-24 12:58:37
【问题描述】:
$('img.clientImage').live('hover', function () {
    if ($('div#ClientImageHover').length > 0) {
        $('div#ClientImageHover').remove();
    } else {
        $('<div id="ClientImageHover">Change Image</div>').insertAfter($(this));
        $('div#ClientImageHover').css({ 'top': $(this).position().top });
    }
})

现在如果我将鼠标悬停在 #ClientImageHover 上会发生什么。你猜对了,它会开始快速闪烁。因为.clientImage 上有一个mouseout 事件。 我需要在此处创建元素并将其附加在img 之后,然后将其放置在其顶部。这工作正常,但是在将鼠标悬停在 #ClientImageHover 上时遇到问题。当鼠标悬停在该div上时,如何继续正常显示该div并保持当前状态?

谢谢。

【问题讨论】:

  • 为什么不将它们都包含在一个共同的父级中并将悬停事件绑定到该父级?
  • 好吧,img 在许多不同的页面上重复出现。我认为这样我可以避免在每一页上重复&lt;div&gt; 行。并在需要时从 dom 中创建/删除元素。
  • 创建jsfiddle 来理解问题会很容易。

标签: javascript jquery html css hover


【解决方案1】:

要扩展我的评论,请执行以下操作jsFiddle

HTML:

<div class="container">
    <img class="clientImage"></div>
</div>

JS

$('.container').live('hover', function () {
    if ($('div#ClientImageHover').length > 0) {
        $('div#ClientImageHover').remove();
    } else {
        $('<div id="ClientImageHover">Change Image</div>').appendTo($(this));
        $('div#ClientImageHover').css({ 'top': $(this).position().top });
    }
}); 

【讨论】:

  • 是的,这行得通。谢谢(我会稍等一下,看看是否可以在不添加容器的情况下完成此操作,否则这解决了 + 1)
【解决方案2】:

您可以将其分解为使用 .mouseenter() 和 .mouseleave()。在img.clientImage 上使用 .mouseenter() 然后只在$('div#ClientImageHover').mouseleave(); 上删除它

http://jsfiddle.net/gkkxG/

【讨论】:

  • 我需要在 .clientImage mouseleave 上删除它并在 .clientImage mouseenter 上显示它。并且只有在鼠标悬停时才显示#ClientImageHover,只有在它超出.clientImage时才将其删除
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-08-24
  • 2011-03-02
  • 2011-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多