【问题标题】:Hover over image to show buttons and don't trigger when hovering over actual buttons将鼠标悬停在图像上以显示按钮,并且在悬停在实际按钮上时不触发
【发布时间】:2011-04-26 04:33:55
【问题描述】:

我试图让按钮在悬停在图像上时出现。以下作品:


    jQuery('.show-image').mouseenter(function() {
 jQuery('.the-buttons').animate({
  opacity: 1
 }, 1500);
}).mouseout(function() {
 jQuery('.the-buttons').animate({
  opacity: 0
 }, 1500); 
});

但是,当从图像移动到按钮(在图像上方)时,会触发 mouseout/mouseenter,因此按钮会淡出然后淡入(按钮与图像具有相同的类,否则它们只是保持淡出)。我怎样才能防止这种情况触发?我还使用 jQuery 的悬停尝试了上面的代码;相同的结果。这是显示不透明度为 1 的按钮的图像的详细信息(因为我在图像上方):

http://i.stack.imgur.com/egeVq.png

提前感谢您的任何建议。

【问题讨论】:

    标签: javascript jquery hover


    【解决方案1】:

    最简单的解决方案是将两者放在同一个父级div 中,并为父级div 提供show-image 类。

    我喜欢使用 .hover() 来节省一些击键。 (所有悬停都是实现 .mouseenter().mouseleave(),但您不必输入它们)

    此外,淡化$(this).find(".the-buttons") 非常重要,这样您只需更改悬停在div 上的按钮,否则您将更改整个页面上的所有.the-buttons.find() 只是寻找后代。

    最后,.animate() 会起作用,但为什么不直接使用 .fadeIn().fadeOut()

    JS:

    jQuery(function() {                                              // <== Doc ready
    
        jQuery(".the-buttons").hide();                  // Initially hide all buttons
    
        jQuery('.show-image').hover(function() {
             jQuery(this).find('.the-buttons').fadeIn(1500);         // use .find() !
        }, function() {
            jQuery(this).find('.the-buttons').fadeOut(1500);         // use .find() !
        });
    });
    

    Try it out with this jsFiddle

    HTML: - 像这样的

    <div class="show-image">
        <img src="http://i.stack.imgur.com/egeVq.png" />
        <input class="the-buttons" type="button" value=" Click " />
    </div>​
    

    CSS: - 像这样的东西。您的可能会有所不同。

    div {
        position: relative;
        float:left;
        margin:5px;}
    div input {
        position:absolute;
        top:0;
        left:0; }​
    

    【讨论】:

      【解决方案2】:

      把图片和按钮放在同一个div里,然后把mouseover/mouseout事件放到这个div上。无论您的鼠标是在按钮还是图像上,它仍然会在 div 上。

      我也不确定mouseenter(...).mouseout(...) 是否有效。我总是用hover(..., ...)

      【讨论】:

      • 是的,我没见过“mouseenter”用得太多,但我见过“mouseover”用得很多。
      • [ .hover() ](api.jquery.com/hover) 只是.mouseenter().mouseleave()的快捷实现
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-06
      • 1970-01-01
      • 2016-10-30
      • 1970-01-01
      相关资源
      最近更新 更多