可拖动DIV层的实现方法

CSS:

* {
    margin: 0;
    padding: 0;
    border: none;
}
body,
html {
    height: 100%;
    width: 100%;
}
.drag-box {
    user-select: none;
    background: #f0f0f0;
    z-index: 2147483647;
    position: fixed;
    left: 0;
    top: 0;
    width: 200px;
}
#dragBoxBar {
    align-items: center;
    display: flex;
    justify-content: space-between;
    background: #ccc;
    width: 100%;
    height: 40px;
    cursor: move;
    user-select: none;
}
    .no-select {
    user-select: none;
}
    .pointer-events {
    pointer-events: none;
}
.no-border {
    border: none;
}
#injectedBox {
    height: 160px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 2rem;
    background: #eee;
}

Js:

var injectedHTML = document.createElement("div");
    injectedHTML.innerHTML = '<dragBox id="dragBox" class="drag-box">\
  <dragBoxBar id="dragBoxBar" class="no-select"></dragBoxBar>\
  <injectedBox id="injectedBox">CONTENT</injectedBox>\
  </dragBox>';

document.body.appendChild(injectedHTML);

var isMouseDown,
    initX,
    initY,
    height = injectedBox.offsetHeight,
    width = injectedBox.offsetWidth,
    dragBoxBar = document.getElementById('dragBoxBar');

dragBoxBar.addEventListener('mousedown', function(e) {
    isMouseDown = true;
    document.body.classList.add('no-select');
    injectedBox.classList.add('pointer-events');
    initX = e.offsetX;
    initY = e.offsetY;
    dragBox.style.opacity = 0.5;
})

dragBoxBar.addEventListener('mouseup', function(e) {
    mouseupHandler();
})

document.addEventListener('mousemove', function(e) {
    if (isMouseDown) {
        var cx = e.clientX - initX,
            cy = e.clientY - initY;
        if (cx < 0) {
            cx = 0;
        }
        if (cy < 0) {
            cy = 0;
        }
        if (window.innerWidth - e.clientX + initX < width + 16) {
            cx = window.innerWidth - width;
        }
        if (e.clientY > window.innerHeight - height - dragBoxBar.offsetHeight + initY) {
            cy = window.innerHeight - dragBoxBar.offsetHeight - height;
        }
        dragBox.style.left = cx + 'px';
        dragBox.style.top = cy + 'px';
    }
})

document.addEventListener('mouseup', function(e) {
    if (e.clientY > window.innerWidth || e.clientY < 0 || e.clientX < 0 || e.clientX > window.innerHeight) {
        mouseupHandler();
    }
});

function mouseupHandler() {
    isMouseDown = false;
    document.body.classList.remove('no-select');
    injectedBox.classList.remove('pointer-events');
    dragBox.style.opacity = 1;
}

演示链接
https://codepen.io/2bt/full/yXajgK/

Last modification:June 27th, 2020 at 04:03 pm
如果觉得我的文章对你有用,请随意赞赏