前端页面鼠标移动监控(鼠标运动、鼠标监控)鼠标防抖处理、mousemove、debounce()、事件停止触发、超时触发

文章目录

代码

html 复制代码
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>页面标题</title>
    <link rel="stylesheet" href="styles.css">
    <script src="script.js" defer></script>
    <style>
        .box {
            width: 200px; /* 设置宽度 */
            height: 200px; /* 设置高度 */
            background-color: lightblue; /* 设置背景颜色 */
            border: 1px solid #000; /* 可选: 添加边框 */
            display: flex; /* 使内容居中 */
            justify-content: center; /* 水平居中 */
            align-items: center; /* 垂直居中 */
            font-size: 24px; /* 设置字体大小 */
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <script>
        // 1. 利用防抖实现性能优化
        // 需求: 鼠标在盒子上移动,里面的数字就会变化 +1
        const box = document.querySelector('.box');
        let i = 1;

        function mouseMove() {
            box.innerHTML = i++;
            console.log(i);
        }

        // 添加事件
        box.addEventListener('mousemove', mouseMove);
    </script>
</body>

</html>

使用lodashjs库debounce函数做防抖处理(只有鼠标移动停止并超过一定时间,才会触发)

html 复制代码
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>页面标题</title>
    <link rel="stylesheet" href="styles.css">
    <!-- 引入 lodash 库,用于实现防抖效果 -->
    <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
    <script src="script.js" defer></script>
    <style>
        .box {
            width: 200px; /* 设置盒子的宽度 */
            height: 200px; /* 设置盒子的高度 */
            background-color: lightblue; /* 设置盒子的背景颜色 */
            border: 1px solid #000; /* 可选: 添加边框 */
            display: flex; /* 使用 flexbox 布局 */
            justify-content: center; /* 水平居中内容 */
            align-items: center; /* 垂直居中内容 */
            font-size: 24px; /* 设置字体大小 */
        }
    </style>
</head>

<body>
    <div class="box"></div> <!-- 创建一个盒子元素 -->
    <script>
        // 选择盒子元素
        const box = document.querySelector('.box');
        let i = 1; // 初始化计数器

        // 使用 lodash 的 debounce 方法创建防抖函数
        // 当鼠标移动时,只有在停止移动 300 毫秒后,才会更新盒子中的数字
        const mouseMove = _.debounce(function() {
            box.innerHTML = i++; // 更新盒子中的内容为当前计数器的值,并自增
        }, 300); // 设置防抖时间为 300 毫秒

        // 为盒子添加鼠标移动事件监听器
        box.addEventListener('mousemove', mouseMove);
    </script>
</body>

</html>

手写防抖函数

html 复制代码
// 手写防抖函数
// 核心是利用 setTimeout定时器来实现
// 1.声明定时器变量
// 2.每次鼠标移动(事件触发)的时候都要先判断是否有定时器,如果有先清除以前的定时器
// 3.如果没有定时器,则开启定时器,存入到定时器变量里面
// 4.定时器里面写函数调用

写法1

html 复制代码
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>页面标题</title>
    <link rel="stylesheet" href="styles.css">
    <!-- 引入 lodash 库(可选,已不再使用) -->
    <script src="script.js" defer></script>
    <style>
        .box {
            width: 200px; /* 设置盒子的宽度 */
            height: 200px; /* 设置盒子的高度 */
            background-color: lightblue; /* 设置盒子的背景颜色 */
            border: 1px solid #000; /* 可选: 添加边框 */
            display: flex; /* 使用 flexbox 布局 */
            justify-content: center; /* 水平居中内容 */
            align-items: center; /* 垂直居中内容 */
            font-size: 24px; /* 设置字体大小 */
        }
    </style>
</head>

<body>
    <div class="box"></div> <!-- 创建一个盒子元素 -->
    <script>
        // 选择盒子元素
        const box = document.querySelector('.box');
        let i = 1; // 初始化计数器
        let timer; // 声明定时器变量

        // 手写防抖函数
        const mouseMove = function() {
            // 每次鼠标移动(事件触发)的时候都要先判断是否有定时器
            if (timer) {
                clearTimeout(timer); // 如果有,先清除以前的定时器
            }
            // 开启定时器,存入到定时器变量里面
            timer = setTimeout(() => {
                box.innerHTML = i++; // 更新盒子中的内容为当前计数器的值,并自增
                console.log(i); // 输出当前计数器的值
            }, 300); // 设置防抖时间为 300 毫秒
        };

        // 为盒子添加鼠标移动事件监听器
        box.addEventListener('mousemove', mouseMove);
    </script>
</body>

</html>

写法2(注意addEventListener监听函数的第二个参数接收的是一个函数,需要构造一个匿名返回函数)

html 复制代码
<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>页面标题</title>
    <!-- <link rel="stylesheet" href="styles.css"> -->
    <!-- <script src="script.js" defer></script> -->
    <style>
        .box {
            width: 200px;
            /* 设置盒子的宽度 */
            height: 200px;
            /* 设置盒子的高度 */
            background-color: lightblue;
            /* 设置盒子的背景颜色 */
            border: 1px solid #000;
            /* 可选: 添加边框 */
            display: flex;
            /* 使用 flexbox 布局 */
            justify-content: center;
            /* 水平居中内容 */
            align-items: center;
            /* 垂直居中内容 */
            font-size: 24px;
            /* 设置字体大小 */
        }
    </style>
</head>

<body>
    <div class="box"></div> <!-- 创建一个盒子元素 -->
    <script>
        // 选择盒子元素
        const box = document.querySelector('.box');
        let i = 1; // 初始化计数器
        let timer; // 声明定时器变量

        // 鼠标移动事件
        function mouseMove() {
            box.innerHTML = i; // 显示当前计数器值
            i++; // 更新计数器
            console.log(i);
        }

        // 防抖函数
        function debounce(fn, delay) {
            return function () {
                console.log("防抖函数被调用"); // 添加调试信息
                if (timer) {
                    clearTimeout(timer);
                }
                timer = setTimeout(() => {
                    fn(); // 调用传入的函数
                }, delay);
            };
        }

        // 为盒子添加鼠标移动事件监听器
        box.addEventListener('mousemove', debounce(mouseMove, 300));
    </script>
</body>

</html>
相关推荐
东方小月4 小时前
从零开发一个 Coding Agent(四):使用状态机校验大模型事件流
前端·人工智能·后端
Csvn4 小时前
🧩 ESM vs CJS 混用的 7 个「天坑」——从 TypeScript 编译到 Node 与浏览器
前端
Csvn4 小时前
🎯 Web 性能 API 集合:Performance Observer 的 5 个冷门妙用
前端
Csvn4 小时前
深入 React 闭包陷阱:从根源上理解并根治 stale closure
前端
whyfail4 小时前
前端学 Spring Boot(8):接口为什么越用越慢?
前端·spring boot·后端
用户059540174465 小时前
LangChain 记忆测试踩坑实录:这两个坑让我排查了 4 小时
前端·css
程序员黑豆5 小时前
鸿蒙应用开发:@Monitor 装饰器使用教程
前端·harmonyos
SamChan906 小时前
在Web应用中集成PDF多语言翻译功能:PDFTranslator API实战指南
前端·python·ai·pdf·yapi·机器翻译
kyriewen6 小时前
AI Agent 9秒删光了生产数据库——我给自己的项目做了5个紧急检查
前端·ai编程·claude
IT_陈寒6 小时前
JavaScript的this又双叒叕让我怀疑人生了
前端·人工智能·后端