原生JS实现拖拽鼠标绘画

2020-11-26 15:21:29 浏览数 (1)

分享一个用原生JS实现的拖拽鼠标绘画的小Demo,效果如下:

以下是代码实现,欢迎大家复制粘贴。

代码语言:javascript复制
<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>原生JS实现拖拽鼠标绘画</title>
    <style>
        div {
            width: 10px;
            height: 10px;
            border-radius: 5px;
            background: red;
            position: absolute;
        }
    </style>
    <script>
        window.onload = function () {

            var aDiv = document.getElementsByTagName('div');
            var i = 0;

            document.onmousemove = function (ev) {

                var oEvent = ev || event;
                // 让DIV跟着鼠标轨迹运动
                for (i = aDiv.length - 1; i > 0; i--) {
                    aDiv[i].style.left = aDiv[i - 1].style.left;
                    aDiv[i].style.top = aDiv[i - 1].style.top;
                };

                aDiv[0].style.left = oEvent.clientX   'px';
                aDiv[0].style.top = oEvent.clientY   'px';
            };
        };
    </script>
</head>

<body>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
</body>

</html>

0 人点赞