纯js拖拽div

function testing() {
    let drag = document.getElementById('zxTempateShowArea');
    drag.onmousedown = function (e) {
        let diffX = e.clientX - drag.offsetLeft;
        let diffY = e.clientY - drag.offsetTop;

        if (typeof drag.setCapture !== 'undefined') {
            drag.setCapture();
        }
        document.onmousemove = function (e) {
            let left = e.clientX - diffX;
            let top = e.clientY - diffY;
            if (left < 0) {
                left = 0
            } else if (left > window.innerWidth - drag.offsetWidth) {
                left = window.innerWidth - drag.offsetWidth
            }
            if (top < 0) {
                top = 0
            } else if (top > window.innerHeight - drag.offsetHeight) {
                top = window.innerHeight - drag.offsetHeight
            }

            drag.style.left = left + 'px'
            drag.style.top = top + 'px'
        };
        document.onmouseup = function (e) {
            console.log('this', this);
            this.onmousemove = null;
            this.onmouseup = null;
            if (typeof drag.releaseCapture !== 'undefined') {
                drag.releaseCapture()
            }
        }
    }
}

你可能感兴趣的:(纯js拖拽div)