在指定区域四个方向画小方块

代码

<!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:800px;
            height:600px;
            margin:10px auto;
            border:5px solid #000;
        }
    </style>
</head>
<body>
    <div id="box"></div>

    <script>
        /*
            1.onmousedown
            2.onmousemove
            3.onmouseup
        */
        var box = document.getElementById('box');
        box.onmousedown = function(ev){
            var eve = event || ev;
            var startX = eve.clientX;  // 起始坐标
            var startY = eve.clientY;
            var newDiv = document.createElement('div');
            newDiv.style.border = '2px solid green';
            newDiv.style.position = 'absolute';

            box.onmousemove = function(ev){
                var eve = event || ev;
                var endX = eve.clientX; // 移动中的坐标
                var endY = eve.clientY; // 移动中的坐标

                // 小方块坐标
                newDiv.style.left = Math.min(startX,endX) + 'px';
                newDiv.style.top = Math.min(startY,endY) + 'px';

                // 小方块宽高
                newDiv.style.width = Math.abs(endX - startX) + 'px';
                newDiv.style.height = Math.abs(endY - startY) + 'px';

            }

            box.appendChild(newDiv);

            // 鼠标抬起,将移动和抬起都置空
            box.onmouseup = function(){
                box.onmousemove = box.onmouseup = null;
            }
        }
    </script>
</body>
</html>

 

效果

posted @ 2020-07-09 20:53  石海莹  阅读(265)  评论(0编辑  收藏  举报