jQuery setTimeout

前端 未结 6 2352
刺人心
刺人心 2021-02-15 11:32

I\'d like to add a timeout to this tooltip code so it only displays if the mouse hovers over it after a while rather than immediately... I tried adding the setTimeout()

相关标签:
6条回答
  • 2021-02-15 12:14

    One option is to use the hoverIntent plugin to accomplish what you want.

    0 讨论(0)
  • 2021-02-15 12:16
    var my_timer;
    $('.mcTxb').hover(
        function () {
            my_timer = setTimeout(function () {
                //do work here
            }, 500);
        },
        function () {
            clearTimeout(my_timer);
        }
    );
    

    This will wait half a second before doing whatever when you mouseover the element and the whatever will not happen if you mouseout within the half second.

    0 讨论(0)
  • 2021-02-15 12:27

    This question is old, but I thought I answer it for others. The main reason the timeout was not working was the case of "setTimeOut" . You cant camel hump the Out part. Its "setTimeout".

    0 讨论(0)
  • 2021-02-15 12:37

    As you're using animation, you can use .delay() to defer the appearance of your tooltip:

    $(mcTooltip).text(mcHoverText).delay(1000).show('fast');
    

    In your mouseout function, use .stop to cancel any existing delays or animations, and then hide the tooltip:

    $(mcTooltip).stop(true).hide('fast');
    
    0 讨论(0)
  • 2021-02-15 12:37
    1. Use hover() instead, it's less code (and that's always good, IMO).

    Like so:

    function mcToolTip() {
        $(".mcTxb").hover(function(){
            // mouseover stuff here
            $("element").delay(3000).show(); // 3 second delay, then show
        }, function(){
            // mouseout stuff here
        });
    }
    
    0 讨论(0)
  • 2021-02-15 12:37

    setTimeout is does not work on mouseover or hover. It is safe to use .delay().

    setTimeout(function(){
        $(mcTooltip).text(mcHoverText).show('fast');
    }, 300);
    
    // use this instead.
    
    $(mcTooltip).text(mcHoverText).delay(3000).show('fast');
    
    0 讨论(0)
提交回复
热议问题