JavaScript实现div鼠标跟随

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .top{
            width: 50px;
            height: 50px;
            position: absolute;
            background-color: red;
        }
    </style>
    <script>
        window.onload = function () {
            var box = document.getElementsByClassName("top")[0];
            document.onmousemove = function (ev) {
                var ev = ev||window.event;
                var scrollleft = document.documentElement.scrollLeft || document.body.scrollLeft;
                var scrolltop = document.documentElement.scrollTop || document.body.scrollTop;
                box.style.left = ev.clientX +"px";
                box.style.top = ev.clientY + "px";
            }
        }
    </script>
</head>
<body>
<div class="top"></div>
</body>
</html>

你可能感兴趣的:(前端,javascript)