将鼠标悬停在图像上以显示按钮,并且在悬停在实际按钮上时不触发

2022-01-22 00:00:00 hover jquery javascript

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

I'm trying to get buttons to appear when hovering over an image. The following works:


    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 的按钮的图像的详细信息(因为我在图像上方):

However, when moving from the image to the button (which is over the image), the mouseout/mouseenter is triggered, so the buttons fade out then fade back in (the buttons have the same class as the image, otherwise they just stay faded out). How can I prevent this from triggering? I've also tried the above code using jQuery's hover; same results. Here's a detail of the image showing the button with opacity 1 (because I'm over the image):

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

提前感谢您的任何建议.

Thanks in advance for any suggestions.

推荐答案

最简单的解决方案是将两者放在同一个父div中,并给父divshow-image 类.

The simplest solution is to put the two in the same parent div and give the parent div the show-image class.

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

I like to use .hover() to save a few key strokes. (alll hover does is implement .mouseenter() and .mouseleave(), but you don't have to type them out)

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

Additionally it's very imporant to fade $(this).find(".the-buttons") so that you only change the button in the hovered over div otherwise you would change all of the .the-buttons on the entire page! .find() just looks for descendants.

最后,.animate() 可以,但为什么不直接使用 .fadeIn().fadeOut()?

Finally, .animate() will work, but why not just use .fadeIn() and .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: - 像这样的

Try it out with this jsFiddle

HTML: - Something like this

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

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

CSS: - Something like this. Yours will likely be different.

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

相关文章