2019年2月26日 星期二

拖曳一個小方塊.......不錯用

<!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>
    <script src="./js_lib/jquery-3.3.1.js"></script>
    <style>
        * {
            padding: 0;
            margin: 0;
            box-sizing: border-box;
        }

        body {
            position: relative;
        }

        div.container_1 {
            height: 1000px;
            background-color: #ffc;
            position: relative;
        }

        #moveEvent {
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            border: 1px dashed;
            z-index: 99999;
            display: none;
            user-select: none;
            opacity: 0;
        }

        #box_1 {
            width: 100px;
            height: 100px;
            position: absolute;
            top: 50px;
            left: 100px;
            z-index: 100;
            background-color: #00F;
            user-select: none;
        }
    </style>
</head>

<body>
    <div id="moveEvent">
        <!-- 全螢幕的畫布 -->
    </div>
    <div class="container_1">
        <p id="box_1">
            box
        </p>
    </div>
    <script>

        // screen 與 #box_1 的座標差
        let topOffset;
        let leftOffset;
        let callback;


        $('#box_1').on('mousedown', function (e) {
            console.dir(e);


            let { left, top } = $(this).position();

            topOffset = top - e.screenY;
            leftOffset = left - e.screenX;
            //-----------------------
            callback = (function (leftOffset, topOffset, x, y) {
                let left = x + leftOffset;
                let top = y + topOffset;

                $('#box_1').css({
                    top: top,
                    left: left
                });
            }).bind(this, leftOffset, topOffset);
            //-----------------------
            $('#moveEvent').css('display', 'block');
        });

        $('#moveEvent').on('mousemove', function (e) {
            console.log('offset:(%s, %s)', e.offsetX, e.offsetY);
            console.log('screen(%s, %s)', e.screenX, e.screenY);

            if(callback){
                callback(e.screenX, e.screenY);
            }
        });

        $('#moveEvent').on('mouseup', function () {
            callback = undefined;
            $('#moveEvent').css('display', '');
        });
    </script>
</body>

</html>