【Vue】关于鼠标移入移出状态防抖

文章目录

概述

鼠标移入切换另一张图,但快速移动鼠标容易出现鼠标已经移出状态还是移入的情况

代码

<template>
  <div class="solution-main" @mouseleave="mouseOut()" @mouseover="mouseIn()">
  鼠标区域
  </div>
</template>

<script setup>
watch(mouseEnter, async (newVal) => {
  if (newVal) {
    // mouseOut
    // ...
  } else {
    // mouseIn
    // ...
  }
})

let mouseTimer = null
// 鼠标移入 false
const mouseIn = () => {
  // 清除之前的计时器,确保只执行最后一次移入
  clearTimeout(mouseTimer)
  mouseTimer = setTimeout(() => {
    mouseEnter.value = false // 移入状态
  }, 100) // 50ms防抖,可根据需要调整
}

// 鼠标移出
const mouseOut = () => {
  // 清除之前的计时器,确保只执行最后一次移出
  clearTimeout(mouseTimer)
  mouseTimer = setTimeout(() => {
    mouseEnter.value = true // 移出状态
  }, 100)
}
</script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Lucky_Turtle

感谢您的打赏,作者会多多努力的

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值