【问题标题】:Dynamic content mouse over and out动态内容鼠标悬停
【发布时间】:2012-09-28 20:52:28
【问题描述】:

我有一些用 json 字符串中的数据创建的 div。其中大部分是图像。在那些动态加载的图像上,并希望在鼠标悬停时显示 div 并在鼠标移出时隐藏。因此我使用了直播功能,在论坛上找到了它。 鼠标悬停功能有效,但不会鼠标移出。因此,当我将鼠标悬停在一张图像上时,会显示 div,但是当我将鼠标移出时,div 仍然可见。对此有何建议?

我的代码

<script type="text/javascript">
    $('.product').live("hover", function() {
        $(this).find('.product').stop(false,true); // get the image where hovering
        $(this).find('div.caption').stop(false,true).fadeIn(100); // and fade in
    },
     function() {
        $(this).find('.product').stop(false,true); // on mouse leave hide it  
        $(this).find('div.caption').stop(false,true).fadeOut(100); // fade out
     });
</script>

更新答案 感谢下面的帮助,我找到了解决方案。

$(".productsGrid .product").live("mouseenter", function() {$(this).find('.product').stop(false,true);
$(this).find('div.caption').stop(false,true).fadeIn(100);})
$(".productsGrid .product").live("mouseleave", function() { $(this).find('.product').stop(false,true);   
$(this).find('div.caption').stop(false,true).fadeOut(100);});

【问题讨论】:

  • 尝试使用 mouseenter 代替 hover
  • @KaiQing - .hover() 绑定 mouseenter 和 mouseleave 事件的处理程序。
  • 如果您使用的是 jquery 1.7.2 或更高版本,您应该切换到 on() 我在使用 1.7.2 时遇到了问题,因为它已被弃用。
  • 你确定 $('.product') 还会在 ($(this).find('.product')) 中找到另一个 $('.product') 吗?
  • 这个代码在 document.ready 中了吗?

标签: jquery


【解决方案1】:

问题是 live 只接受一个函数参数,而不是像 hover 函数那样接受 2 个参数。使用hoverlive 基本上只是将一个函数绑定到mouseentermouseleave

你可以看到解释和解决方案here

但是,除非您使用的是 1.7 之前的 jquery 版本,否则您不应该使用 live,因为它已被弃用。你应该改用on

您的代码将如下所示:

$(STATIC ANCESTOR).on({ 
        mouseenter: 
           function() 
           { 

           }, 
        mouseleave: 
           function() 
           { 

           } 
       }, ".product"
    ); 

STATIC ANCESTOR 被替换为 .product 元素的祖先元素,该元素不是动态加载的。如果需要,可以使用document,但只能作为最后的手段。

【讨论】:

  • 好的,谢谢...这对我有用!我用正确的答案更新了我的问题,'
猜你喜欢
  • 1970-01-01
  • 2016-05-26
  • 2016-10-27
  • 1970-01-01
  • 1970-01-01
  • 2011-08-04
  • 2018-09-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多