2018年1月26日 星期五

拖曳一個小方塊

<body>
    <div id="t_1">
        <div class="box">

        </div>
    </div>
</body>
<script>
        $(document).ready(function () {

            $('div.box').on('mousedown', function (e) {
                let t1 = e.target;
                let x = e.offsetX;
                let y = e.offsetY;

                $('#t_1').on('mousemove', function (e) {
                    let t2 = e.target;
                    let _x = e.offsetX;
                    let _y = e.offsetY;

                    if (e.target.isEqualNode(e.currentTarget)) {
                        // console.log(_x);

                        $(t1).css({
                            left: (_x - x),
                            top: (_y - y)
                        });
                    }
                });
            });

            $('#t_1').on('mouseup', function (e) {
                $('#t_1').off('mousemove');
            });

        });
    </script>