div拖拽

function component() {
    let element = document.createElement('div');
    let offX,offY
    let drag = false
    element.innerHTML = 'Hello, world');
    element.classList.add('box')
    element.style.left = '50px'
    element.style.top = '50px'
    element.addEventListener('mousedown',(e) => {
      drag = true
      offX = e.offsetX   //鼠标相对容器的距离
      offY = e.offsetY
    })
    document.addEventListener('mousemove',(e) => {
      if(drag) {
        element.style.left = Math.max(e.clientX - offX,0) + 'px'   //防止超出容器范围
        element.style.top = Math.max(e.clientY - offY, 0) + 'px'
      }
    })
    document.addEventListener('mouseup',(e) => {
      drag = false
    })

    return element;
  }
  
  document.body.appendChild(component());

div为绝对定位,body为相对定位

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