移動端、pc端拖動元素移動

1. 移動端拖動元素移動

<!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;
        }
        
        div {
            width: 100px;
            height: 100px;
            background-color: aqua;
            position: absolute;
            top: 0;
            left: 0;
        }
    </style>
</head>

<body>
    <div class="one two"></div>
    <script>
        var div = document.querySelector('div');
        div.addEventListener('touchstart', function(e) {
            var x = e.targetTouches[0].pageX - this.offsetLeft;
            var y = e.targetTouches[0].pageY - this.offsetTop;

            document.addEventListener('touchmove', move);

            function move(e) {
                div.style.left = e.targetTouches[0].pageX - x + 'px';
                div.style.top = e.targetTouches[0].pageY - y + 'px';
            }

            document.addEventListener('touchend', function() {
                document.removeEventListener('touchmove', move);
            })
        })
    </script>
</body>

</html>

2. pc端拖動元素移動

<!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;
        }
        
        div {
            width: 100px;
            height: 100px;
            background-color: aqua;
            position: absolute;
            top: 0;
            left: 0;
        }
    </style>
</head>

<body>
    <div class="one two"></div>
    <script>
        var div = document.querySelector('div');
        
        div.addEventListener('mousedown', function(e) {
            console.log();
            var x = e.pageX - div.offsetLeft;
            var y = e.pageY - div.offsetTop;
            /* 盒子內的距離 */

            function move(e) {
                /* 盒子的距離 */
                div.style.left = e.pageX - x + 'px';
                div.style.top = e.pageY - y + 'px';
            }
            document.addEventListener('mousemove', move);

            document.addEventListener('mouseup', function() {
                document.removeEventListener('mousemove', move);
            })
        })
    </script>
</body>

</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章