zoukankan      html  css  js  c++  java
  • JavaScript盒子拖拽的简单案例

    让小盒子在大盒子中拖动,不能超出大盒子,如下图:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <style>
            * {
                margin: 0;
                padding: 0;
            }
    
            .bigBox {
                position: relative;
                 500px;
                height: 500px;
                border: 1px solid #000;
                margin: 50px auto;
            }
    
            .box {
                position: absolute;
                left: 0;
                top: 0;
                 100px;
                height: 100px;
                background: red;
            }
        </style>
    </head>
    <body>
        <div class="bigBox">
            <div class="box"></div>
        </div>
        <script>
            var $bigBox = document.querySelector('.bigBox');
            var $box = document.querySelector('.box')
    
            // 鼠标按下
            $box.onmousedown = function (e) {
                e = e || window.event;
                // 获取最大移动距离
                var maxX = $bigBox.clientWidth - $box.offsetWidth,
                    maxY = $bigBox.clientHeight - $box.offsetHeight;
                // 获取鼠标偏移量
                var x = e.offsetX,
                    y = e.offsetY;
                // 获取大盒子的偏移量
                var left = $bigBox.offsetLeft,
                    top = $bigBox.offsetTop;
    
                document.onmousemove = function (e) {
                    e = e || window.event;
                    // 小盒子的移动距离
                    var moveX = e.pageX - x - left,
                        moveY = e.pageY - y - top;
                    if (moveX < 0) {
                        moveX = 0;
                    } else if (moveX > maxX) {
                        moveX = maxX;
                    }
                    if (moveY < 0) {
                        moveY = 0;
                    } else if (moveY > maxY) {
                        moveY = maxY;
                    }
    
                    $box.style.left = moveX + 'px';
                    $box.style.top = moveY + 'px';
                }
    
            }
            // 鼠标抬起
            document.onmouseup = function () {
                // 取消时间
                document.onmousemove = null;
            }
        </script>
    </body>
    </html>
  • 相关阅读:
    OpenGL纹理数据块
    MFC应用真彩色图标资源
    PictureConverter命令行图片批量转换工具
    Google Earth6.1 tree
    OpenGL Render On Window Process
    纹理滤波(Texture Filter)
    使用开源OpenCTM进行常用三维格式互导
    《搅基辞》
    访问WebDAV服务
    linux 挂载一个文件夹到另一个文件夹
  • 原文地址:https://www.cnblogs.com/H-Y-Z/p/10510212.html
Copyright © 2011-2022 走看看