可拖曳的div

147 阅读1分钟
        //1 获取元素
        const box = document.querySelector('#box')

        //状态
        let dragging = false
        //坐标
        let position = null
        box.addEventListener('mousedown', function (e) {
            dragging = true // 正在移动
            position = [e.clientX, e.clientY]
            console.log(1)
        })

        document.addEventListener('mousemove', function (e) {
            if (dragging === false) { return } //不要动
            const x = e.clientX
            const y = e.clientY

            //当前移动时的坐标 - 上次坐标的差值
            const diffX = x - position[0]
            const diffY = y - position[1]

            let left = parseInt(box.style.left || 0)
            let top = parseInt(box.style.top || 0)
            // 避免拖拽出可视区
            if (left < 0) {
                left = 0
            } else if (left > window.innerWidth - box.offsetWidth) {
                left = window.innerWidth - box.offsetWidth
            }
            if (top < 0) {
                top = 0
            } else if (top > window.innerHeight - box.offsetHeight) {
                top = window.innerHeight - box.offsetHeight
            }
            box.style.left = diffX + left + 'px'
            box.style.top = diffY + top + 'px'

            //下一次的移动坐标
            position = [x, y]
            console.log(2)
        })

        document.addEventListener('mouseup', function (e) {
            dragging = false
            console.log(3)
        })