【问题标题】:How to make function work when the mouse not moving?鼠标不动时如何使功能起作用?
【发布时间】:2015-08-11 17:11:43
【问题描述】:
$(document).ready(function() {
    var score = 0;

    $("body").mousemove(function() {        
        score++;
        $("#result").val(score);
        console.log(score);
    });

 });

每次移动鼠标分数都会增加,但是我应该如何添加一个函数来减少分数直到鼠标不移动时分数为0?

【问题讨论】:

标签: javascript jquery html web


【解决方案1】:

选项:使用经过的时间。移动鼠标时,检查now() 与上次移动鼠标的时间。使用经过的时间来降低块中的分数。

【讨论】:

  • 我对如何执行选项 2 很感兴趣。
【解决方案2】:

您可以设置一个间隔,如果鼠标不移动则减小该值,并在鼠标移动时清除它,然后重置它,如下所示:

$(document).ready(function() {
    var score = 0, decreaseInterval, intervalTime = 1000;

    function decrease() {
        if (score > 0) score--;
        $("#result").val(score);
    };

    decreaseInterval = setInterval(decrease, intervalTime);

    $("body").mousemove(function(){
        clearInterval(decreaseInterval);
        score ++;
        $("#result").val(score);
        decreaseInterval = setInterval(decrease, intervalTime);
        console.log(score);
    });
});

这是一个演示它工作的小提琴:https://jsfiddle.net/0swrae76/1/

【讨论】:

  • 考虑 JavaScript 事件循环我认为您不需要在每次鼠标移动时都清除和 setInterval。 Intead 我会推荐一次 setInterval 并使用布尔标志来管理事情。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-21
  • 2020-02-02
  • 1970-01-01
相关资源
最近更新 更多