悬停在图像上显示按钮,但在悬停在实际按钮上时不触发。

8

我想在鼠标悬停在图片上时显示按钮。以下代码可行:


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

然而,当鼠标从图片移动到按钮(覆盖在图片上的按钮)时,会触发mouseout/mouseenter事件,导致按钮淡出然后再淡入(如果按钮与图像具有相同的类,则它们只会保持淡出状态)。我该如何防止这种情况的发生?我还尝试使用jQuery的hover方法,但结果相同。以下是显示不透明度为1的按钮的图像细节(因为我在图片上方): http://i.stack.imgur.com/egeVq.png 感谢您提前给出的任何建议。
2个回答

8
最简单的解决方案是将两者放在同一个父级 div 中,并给父级 div 添加 show-image 类。
我喜欢使用 .hover() 来节省一些按键。 (所有 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() !
    });
});

请使用这个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; }​

3
将图片和按钮放在同一个div中,然后将mouseover/mouseout事件放在div上。这样无论您的鼠标是否悬停在按钮或图像上,它仍将悬停在div上。
此外,我不确定mouseenter(...).mouseout(...)是否有效。我总是使用hover(..., ...)。

是的,我很少见到使用“mouseenter”,但我经常看到使用“mouseover”。 - coder_tim
.hover() 简单来说是 .mouseenter().mouseleave() 的快捷实现。 - Peter Ajtai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接