【问题标题】:jquery: only show one div when hoverjquery:悬停时只显示一个div
【发布时间】:2010-09-08 23:22:47
【问题描述】:

大家好,我遇到了这个小脚本的问题。当我将鼠标悬停在 div“项目”上时,两个 div 都显示“深色覆盖”。但我只想要我悬停显示的 div 内部的深色叠加层。这怎么可能?谢谢:)


.item {
position:relative;
width:680px;
height:140px;
}
.dark-overlay {
position:absolute;
width:680px;
height:140px;
background:url(images/bg.png) repeat;
display:none;
}

<div class="item">
   <div class="dark-overlay"></div>
   <img src="my image.jpg" />
</div>

<div class="item">
   <div class="dark-overlay"></div>
   <img src="my image.jpg" />
</div>

$(function() {
   $(".item").hover(function() {
      $(".dark-overlay").show();
   });
});

【问题讨论】:

    标签: jquery hover show


    【解决方案1】:

    你只能在你悬停的那个里面找到.dark-overlay,像这样:

    $(function() {
       $(".item").hover(function() {
          $(this).find(".dark-overlay").show();
       });
    });
    

    或者,更有可能的是,您希望它在离开时也隐藏起来,在这种情况下,您应该像这样使用.toggle()

    $(function() {
       $(".item").hover(function() {
          $(this).find(".dark-overlay").toggle();
       });
    });
    

    You can give it a try here,或者添加一点淡入淡出动画,like this

    【讨论】:

    • 非常感谢你,尼克! :)
    • 你能告诉我,当我不悬停 .item 时,我是如何淡化 .dark-overlay 的吗? :)
    • @Sebastian - 查看答案底部的演示 :)
    • 请注意,此示例使用 jQuery 1.4.2。如果您使用的是 1.3.2,则行为会有所不同。我认为区别在于 .hover() 属性,但我不确定它们发生了什么变化。
    • @Litso - 这在 1.3.2 中是一样的,在幕后事件模型由于 其他 原因发生了一些变化,但没有任何影响:)
    【解决方案2】:

    这应该可以解决问题,悬停事件处理程序接受两个参数(鼠标移入和鼠标移出),然后将 .dark-overlay 搜索限制为“this”(当前 .item 元素)内的项目

    $('.item').hover(
      function() { // Mouse in
        $('.dark-overlay', this ).fadeIn();
      },
      function() { // Mouse out
        $('.dark-overlay', this ).fadeOut();
      }
    );
    

    【讨论】:

      猜你喜欢
      • 2019-03-22
      • 1970-01-01
      • 2012-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多