Add delay before .hide() w/jQuery

前端 未结 2 1374
后悔当初
后悔当初 2020-12-07 03:59

I have a simple code that keeps an element visible while a mouse hovers over it and hides it once the mouse is out.:

$(\".item\").hover(
    function () {
           


        
相关标签:
2条回答
  • 2020-12-07 04:41

    .hide() without any arguments doesn't use the effects queue (and won't have to wait for .delay()). Instead, you could use $(this).delay(500).hide(0);

    0 讨论(0)
  • 2020-12-07 05:03
    var my_timer;
    $(".item").hover(
        function () {
            clearTimeout(my_timer);
            $(this).show();
        }, 
        function () {
            var $this = $(this);
            my_timer = setTimeout(function () {
                $this.hide();
            }, 500);
        }                       
    );
    

    Here is a demo: http://jsfiddle.net/e3cNK/1/

    If you want to be able to re-show the element after it has been hidden then you want to change the opacity of the element rather than changing its display to none. This will keep the elements in the regular flow of the page so when the user mouse-overs the hidden element it can show again:

    var my_timer;
    $(".item").hover(
        function () {
            var $this = $(this);
            $this.text('Mouse-Over');
            clearTimeout(my_timer);
            $this.stop().fadeTo(250, 1);
        },
        function () {
            var $this = $(this);
            $this.text('Mouse-Out');
            my_timer = setTimeout(function () {
                $this.fadeTo(250, 0);
            }, 500);
        }                       
    );
    

    Here is a demo: http://jsfiddle.net/e3cNK/2/

    0 讨论(0)
提交回复
热议问题