jQuery setTimeout of a hover function

2019-08-18 05:16发布

问题:

my .hover function work fine but now the .hover function needs to wait 2 seconds to start but something isnt working with my code.

JS Code

setTimeOut(function(){
        $('#sectionNews').hover(
            function() {

                    $(this).find('.underlay_wrapper').animate({
                        height: '85px', opacity: '1'
                    }, 1000 );

            },function() {
                $(this).find('.underlay_wrapper').animate({
                    height: '0px', opacity: '0'
                },500);

            }
        );
    }, 200);

回答1:

If you want the hover code to start 2 seconds after hovering you must put the setTimeout inside hover

var tOut = null;
$('#sectionNews').hover(function () {
   var $this=$(this);
  tOut=  setTimeout(function () { //Here
        $this.find('.underlay_wrapper').animate({
            height: '85px',
            opacity: '1'
        }, 1000);
    }, 2000);
}, function () {
    var $this = $(this);
    clearTimeout(tOut);
    setTimeout(function () {//here also if you want it to setTimeout when hover out
        $this.find('.underlay_wrapper').animate({
            height: '0px',
            opacity: '0'
        }, 500);
    }, 2000);
});

Update

You could use .delay(2000) instead of setTimeout for animating elements

$('#sectionNews').hover(function () {
        $(this).find('.underlay_wrapper').delay(2000).animate({
            height: '85px',
            opacity: '1'
        }, 1000);
}, function () {
        $(this).find('.underlay_wrapper').delay(2000).animate({
            height: '0px',
            opacity: '0'
        }, 500);
});

DEMO



回答2:

try like this

$('#sectionNews').hover(function () {
        var a = setInterval(function () {
            $(this).find('.underlay_wrapper').animate({
                height: '85px', opacity: '1'
            }, 1000);
            clearInterval(a);

        }, 2000);
    });