【问题标题】:Time Delay in javascript in a switch div function切换div函数中javascript中的时间延迟
【发布时间】:2016-04-27 17:03:28
【问题描述】:

我对 Javascript 比较陌生。我最近在悬停时发现了这个switch div function。我也插入了下面的代码。我试图插入在鼠标从 div 中移除后发生的时间延迟。这样它就不会立即变回原始文本。我该怎么做呢?我想我需要使用setTimeOut(),但我还没有想出成功实现它的方法。

$('.switch').hover(function() {
        $(this).find('.avg_words').hide();
        $(this).find('.avg_num').show();
    }, function() {
        $(this).find('.avg_num').hide();
        $(this).find('.avg_words').show();
});
.avg_num {
	display: none;
}
<div class="switch">
<div class="avg_words float_left">
  A+ (hover to see score)  
</div>
<div class="avg_num">
  AVG = 98.35%
</div>
</div>

【问题讨论】:

  • setTimeout(function(){ /* code here */ }, delay); 或... setTimeout(functionName, delay);

标签: javascript html time switch-statement delay


【解决方案1】:

setTimeout 这是超时对象的this。这就是为什么它不起作用

$('.switch').hover(function() {
        $(this).find('.avg_words').hide();
        $(this).find('.avg_num').show();
    }, function() {
        var hoverObj = this;
        setTimeout(function() {
            $(hoverObj ).find('.avg_num').hide();
            $(hoverObj ).find('.avg_words').show();
        }, 1000);
    });

【讨论】:

  • 好答案,请注意:当想要保存对this 的引用时,最好使用_thisself 作为变量名。
  • @ArcaneCraeda 感谢您的建议。下次我会记住这一点:)。
【解决方案2】:

您可以使用 setTimeout 延迟运行函数。不要忘记存储间隔,以免悬停时出现任何奇怪的抖动。

var i;
$('.switch').hover(function() {
        clearInterval(i);
        $(this).find('.avg_words').hide();
        $(this).find('.avg_num').show();
    }, function() {
        clearInterval(i);
        i = setTimeout(function() {
          $(this).find('.avg_num').hide();
          $(this).find('.avg_words').show();
        }.bind(this), 500);
});

【讨论】:

    【解决方案3】:

    尝试使用setTimeout

    $('.switch').hover(function() {
        $(this).find('.avg_words').hide();
        $(this).find('.avg_num').show();
    }, function() {
        var _this = this;
        setTimeout(function() {
            $(_this).find('.avg_num').hide();
            $(_this).find('.avg_words').show();
        }, 1000); //delay in milliseconds, here 1s
    });
    

    JSFiddle

    【讨论】:

    • 感谢您的回答!我试过了,但由于某种原因,它卡在avg_num 上,1 秒后不会返回avg_words
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-22
    • 1970-01-01
    • 2011-10-08
    • 1970-01-01
    • 2016-05-27
    • 1970-01-01
    相关资源
    最近更新 更多