html+css+js实现小红点跟随鼠标移动

html 复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{
            margin: 0;padding: 0;
        }
        .box{
            width: 100vw;
            height: 100vh;
            /* 该元素不能对鼠标事件做出反应 */
            /* pointer-events: none; */
            overflow: hidden;
            background: pink;
        }
        .dot {
            width: 20px;
            height: 20px;
            background-color: red;
            border-radius: 50%;
            position: absolute;
            top: 0px;
            left: 0px;
            transform: translate(-100%,-100%);
            /* 小球跟随鼠标的速度 越小越快 */
            transition: all 0.1s;
        }
    </style>
</head>

<body>
    <div class="box">
        <div class="dot"></div>
    </div>
    <script>
        const rdot = document.querySelector('.dot');
        // 监听事件:鼠标被移动
        document.addEventListener('mousemove',function(e){
            rdot.style.top = e.pageY + 'px';
            rdot.style.left = e.pageX + 'px';
        })
        // 鼠标指针移动到元素上时触发
        document.addEventListener('mouseenter',function(){
            rdot.style.opacity = 1
        })
        // 鼠标指针移出元素时触发
        document.addEventListener('mouseleave',function(){
            rdot.style.opacity = 0
        })
    </script>
</body>

</html>
相关推荐
JohnYan1 分钟前
Bun技术评估 - 05 SQL
javascript·后端·bun
前端农民晨曦4 分钟前
深入浏览器事件循环与任务队列架构
前端·javascript·面试
Spider_Man19 分钟前
JavaScript对象那些坑:初学者必踩的“陷阱”与进阶秘籍
前端·javascript
我在北京coding41 分钟前
Uncaught ReferenceError: process is not defined
前端·javascript·vue.js
张成AI1 小时前
A2A JS SDK 完整教程:快速入门指南
javascript·agent·a2a
子言sugar1 小时前
CSS高效开发必备小技巧集锦
css
baozj1 小时前
一次表单数据复用引发的 Bug:理解 Vue 中的 data 为何是函数
前端·javascript·vue.js
LRH1 小时前
JS基础 - instanceof 理解及手写
前端·javascript
小小神仙1 小时前
JSCommon系列 - 为什么前端没有 Apache Commons?
前端·javascript·设计模式
一头小鹿1 小时前
【JS】手写显示绑定改变this指向的方法call、apply、bind | 笔记整理
javascript