JavaScriptで要素をドラッグして移動するサンプル(完成版)

<img id="ball" src="https://js.cx/clipart/ball.svg" width="40" height="40" alt="">
#ball {
  position: absolute;
  cursor: grab;
  z-index: calc(Infinity);
}
const ball = document.getElementById('ball')

ball.onpointermove = function(event) {
  if (event.buttons) {
    const screenWidth = window.innerWidth
    const screenHeight = window.innerHeight

    this.style.left = Math.max(0, Math.min(this.offsetLeft + event.movementX, screenWidth - this.offsetWidth)) + 'px'
    this.style.top = Math.max(0, Math.min(this.offsetTop + event.movementY, screenHeight - this.offsetHeight)) + 'px'
    this.style.cursor = 'grabbing'
    this.draggable = false
    this.setPointerCapture(event.pointerId)
  } else {
    this.style.cursor = 'grab'
  }
}

元記事を表示する