[컴] draggable div 만들기

draggable popup / html / js / vue / 드래그 / 팝업 / 움직이는

draggable div 만들기


<!DOCTYPE html>
<html>
<style>
#outer{
  position: absolute; // absolute 을 해야 현재 그려진 화면 위로 그려진다.
}
#mydiv {
  width: 100px;
  z-index: 10;
  text-align: center;
  border: 1px solid #d3d3d3;
}

#mydivheader {
  padding: 10px;
  cursor: move;
  z-index: 10;
  background-color: #2196F3;
  color: #fff;
}
</style>
<body>

<div id='outer'>
    <div id="mydiv">
      <div id="mydivheader">Click here to move</div>
      <p>Move</p>
      <p>this</p>
      <p>DIV</p>
    </div>
</div>

<script>

drag(document.getElementById("outer"));

function drag(wrap /* HTMLElement */, inRange = false) {
  wrap.style.cursor = 'move'
  const container = wrap
  if (!container) {
    return
  }
  const range = {
    left: 0,
    right: 0,
    top: 0,
    bottom: 0
  }
  let startX = 0
  let startY = 0
  let status = ''

  const onMouseMove = (e /* MouseEvent */) => {
    if (status !== 'down') return
    const moveX = e.clientX
    const moveY = e.clientY
    let distX = moveX - startX
    let distY = moveY - startY
    if (inRange) {
      if (distX <= range.left) {
        distX = range.left
      }
      if (distX >= range.right) {
        distX = range.right
      }
      if (distY <= range.top) {
        distY = range.top
      }
      if (distY >= range.bottom) {
        distY = range.bottom
      }
    }
    container.style.left = distX + 'px'
    container.style.top = distY + 'px'
  }

  const onMouseUp = () => {
    status = 'up'
    document.removeEventListener('mousemove', onMouseMove)
    document.removeEventListener('mouseup', onMouseUp)
  }

  wrap.addEventListener('mousedown', (e /* MouseEvent */) => {
    e.preventDefault()
    status = 'down'
    if (inRange) {
      range.left = -((document.documentElement.clientWidth - container.clientWidth) / 2)
      range.right = Math.abs(range.left)
      range.top = -(document.documentElement.clientHeight - container.clientHeight) / 2
      range.bottom = Math.abs(range.top)
    }
    startX = e.clientX - (parseInt(container.style.left) || 0)
    startY = e.clientY - (parseInt(container.style.top) || 0)

    document.addEventListener('mousemove', onMouseMove)
    document.addEventListener('mouseup', onMouseUp)
  })

}
</script>

</body>
</html>


Reference

  1. How To Create a Draggable HTML Element

댓글 없음:

댓글 쓰기