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>
相关推荐
不会敲代码113 小时前
手写 Zustand:三十分钟带你搞懂状态管理库的核心原理
前端·javascript·源码
神奇的程序员13 小时前
重构了自己5年前写的截图插件
前端·javascript·架构
橙淮13 小时前
从优化到安全再到未来 ——JavaScript 全维度技术指南
javascript
诚实可靠王大锤14 小时前
React Native 输入框与按钮焦点冲突解决方案(rn版本0.70.3)
前端·javascript·react native·react.js
zithern_juejin18 小时前
Date/RegExp/Error/ArrayBuffer
javascript
zenRRan18 小时前
Karpathy公开附议:AI Agent 的输出格式,正在从 Markdown 走向 HTML
前端·html
燐妤18 小时前
前端HTML编程5:JavaScript完全指南
前端·javascript·html
八月欢喜18 小时前
【Facebook】 实时消息监控难点解析
javascript·python·facebook
zithern_juejin19 小时前
Map/Set/WeakMap/WeakSet
javascript
Dxy123931021619 小时前
Python 去除 HTML 标签获取纯文本
开发语言·python·html