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) {
    this.style.left = this.offsetLeft + event.movementX + 'px'
    this.style.top = this.offsetTop + event.movementY + 'px'
    this.style.cursor = 'grabbing'
    this.draggable = false
    this.setPointerCapture(event.pointerId)
  } else {
    this.style.cursor = 'grab'
  }
}

元記事を表示する