前言

开发框架为 vue2.x

情景描述

需求是这样的:页面在鼠标悬停(不动)n秒之后,页面进行相应的事件。

比如在我的需求下,是鼠标悬停15秒之后,页面上三个数据弹窗轮询展示。

解决方法

我的思路中 涉及到了三个变量

data(){
  return {
    polling: null,
    timeCount: 0,
    judgeTimer: null,  
  }
}

polling: 是 轮询的时候的一个计时器
timeCount: 是 判断鼠标是否移动的一个控制变量
judgeTimer:是 判断鼠标是否移动的一个计时器

只要鼠标进行了移动,那么 timeCount就会发生变化。
若是15秒内 timeCount没有发生变化,那么就说明此刻鼠标处于悬停状态,就可以进行运行悬停的事件

那么 对于鼠标移动 我们可以给元素绑定 mousemove事件

mouseMove() {
  clearTimeout(this.judgeTimer);
  clearInterval(this.polling);
  this.timer = null;
  this.polling = null;
  this.timeCount = ++this.timeCount % 100;
},

那么对于 timeCount 怎么知道是多久未发生变化呢?

我们可以在watch下对其进行监听

watch: {
  timeCount: {
    handler() {
      this.judgeTimer = null;
      this.polling = null;
      clearTimeout(this.judgeTimer);
      clearInterval(this.polling);
      this.judgeTimer = setTimeout(() => {
        this.play();
      }, delay);
    },
  },
},

至于我嘛的 play 函数 就是我们的具体业务部分了,在play函数内编写轮询的业务,使用 polling 作为计时器。

play() {
  clearInterval(this.polling);
  this.polling = setInterval(() => {
    // 具体业务代码
  }, delay);
},
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。