用js實現可拖動的div

用js實現可拖動的div,其實邏輯很簡單,計算鼠標的移動距離然後設置盒子的位置即可
看看效果
在這裏插入圖片描述
源碼


<!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>
        * {
            padding: 0;
            margin: 0;
        }

        body {
            position: relative;
            width: 100vw;
            height: 100vh;
        }

        .box {
            position: absolute;
            width: 400px;
            height: 400px;
            background: skyblue;
        }
    </style>
</head>

<body>
    <div class="box" id='box'>
    </div>

    <script>
        const box = document.getElementById('box')
        let isDown = false
        let mouse = {}
        box.onmousedown = (e) => {
            isDown = true
            box.style.cursor = 'move'
            //保存初始位置
            mouse = {
                startX: e.clientX,
                startY: e.clientY,
                offsetLeft: box.offsetLeft,
                offsetTop: box.offsetTop,
            }
        }

        box.onmousemove = (e) => {
            if (!isDown) {
                return
            }
            //計算偏移位置
            let offsetLeft = mouse.offsetLeft + e.clientX - mouse.startX
            let offsetTop = mouse.offsetTop + e.clientY - mouse.startY

            //設置偏移距離的範圍[0,window.innerWidth - 400]
            offsetLeft = Math.max(0, Math.min(offsetLeft, window.innerWidth - 400))
            offsetTop = Math.max(0, Math.min(offsetTop, window.innerHeight - 400))
            
            box.style.left = offsetLeft + 'px';
            box.style.top = offsetTop + 'px';

        }
        //當鼠標滑的太快時,容易移出box,所以在window上監聽此事件
        window.onmouseup = () => {
            isDown = false
            box.style.cursor = 'default'
            mouse = null
        }
    </script>

</body>

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