jquery tooltip with delay on show

2020-07-17 14:27发布

问题:

i wrote a very simple tooltip script with pre delay on show.

but i have some problem with my code

i dont want too show the tooltip that has less than 500 ms hover time but i have blink effect because of fadeTo() animation effect

this means when i hover on .imgSpan and then quickly unhover the mouse less than 500 ms, the .img tag will show after 500 ms and quickly hide

here is my code

$(document).ready(function ()
{
    $('.img').css('display','none');
});
$('.imgSpan').hover(
function(){
    $(".imgSpan:hover .img").delay(500).fadeTo(500, 1);
},
function(){
    $(".img").css("display", "none");
    $(".img").fadeTo(0, 0);
}
);

HTML Code:

<span class='imgSpan'>
<a>
<img src='/images/image.png' class='middle' />
</a>
<img class='img' src='image_path' alt='image' />

notes:

  • i dont want to lose animation effect

  • i dont want to use any plugin

回答1:

That is because of a wrong queuing.

To correct that, you can write the CSS line like that:

$(".img").stop(true, true).css("display", "none");

This will clear every animation on the selector and then change the CSS.

Im not sure but I think you can remove the second true on stop. You just have to try it!



回答2:

The selector .imgSpan:hover is incorrect.

Since you've not mentioned HTML, assuming ( by selector mentioned in question which is $(".imgSpan:hover .img") ie child of .imgSpan),

<div class="imgSpan">Hover me
<div class="img">Some</div>
</div>

Here's correct js -

$('.img').css('display','none');
$('.imgSpan').hover(function(){
    $(this).find(".img").delay(1000).fadeTo(500, 1);
},function(){
    $(".img").css("display", "none");
    $(".img").fadeTo(0, 0);
});

Demo here