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>
相关推荐
代码煮茶3 小时前
Vue3 组件库二次封装实战 | 基于 Element Plus 封装企业级 UI 组件库
前端·javascript·vue.js
shen_3 小时前
JS语法:生成器和可迭代对象
javascript
Arman_3 小时前
03 rusty-cat 进阶解析:架构设计、云存储接入、安全模型与长期维护评估
css·安全·rust·文件分片上传·文件分片下载
之歆3 小时前
DAY_11JavaScript BOM与DOM深度解析:底层原理与工程实践(上)
开发语言·前端·javascript·ecmascript
逆yan_3 小时前
🧭 基于 pnpm Workspace 和 Turborepo 的 Monorepo 最佳实践
前端·javascript·架构
Nturmoils4 小时前
书签真正难的不是收藏,而是找回来:我是怎么做这个 Chrome 插件的
javascript·后端·浏览器
HYCS4 小时前
用pixijs实现fabricjs(三):对象继承链和自定义对象
前端·javascript·canvas
biubiubiu_LYQ4 小时前
萌新小白基础篇之JS预编译
javascript
ZC跨境爬虫4 小时前
跟着 MDN 学 HTML day_60:(表单与按钮技能测试实战)
服务器·前端·javascript·数据库·ui·html
张元清4 小时前
React 里不用 setTimeout 的计时器写法:useTimeout、useInterval、useCountDown 和 useRafFn
前端·javascript·面试