要素をドラッグして移動することは、JavaScriptにおいて頻出パターンです。 しかし、それを簡単に実現するコードは意外と知られていません。 <img id="$img" src="https://js.cx/clipart/ball.svg" width="40" height="40"> <script> $img.onpointermove = function(event){ if(event.buttons){ this.style.left = this.offsetLeft + event.movementX + 'px' this.style.top = this.offsetTop + event.movementY + 'px' this.style.position = 'absolute' this.draggable = false this.setPointe
![JavaScriptで要素をドラッグして移動する簡単な方法 - Qiita](https://cdn-ak-scissors.b.st-hatena.com/image/square/d4955515d15a597f7afcc75c1d16936af9a60dbb/height=288;version=1;width=512/https%3A%2F%2Fqiita-user-contents.imgix.net%2Fhttps%253A%252F%252Fcdn.qiita.com%252Fassets%252Fpublic%252Farticle-ogp-background-412672c5f0600ab9a64263b751f1bc81.png%3Fixlib%3Drb-4.0.0%26w%3D1200%26mark64%3DaHR0cHM6Ly9xaWl0YS11c2VyLWNvbnRlbnRzLmltZ2l4Lm5ldC9-dGV4dD9peGxpYj1yYi00LjAuMCZ3PTk3MiZoPTM3OCZ0eHQ9SmF2YVNjcmlwdCVFMyU4MSVBNyVFOCVBNiU4MSVFNyVCNCVBMCVFMyU4MiU5MiVFMyU4MyU4OSVFMyU4MyVBOSVFMyU4MyU4MyVFMyU4MiVCMCVFMyU4MSU5NyVFMyU4MSVBNiVFNyVBNyVCQiVFNSU4QiU5NSVFMyU4MSU5OSVFMyU4MiU4QiVFNyVCMCVBMSVFNSU4RCU5OCVFMyU4MSVBQSVFNiU5NiVCOSVFNiVCMyU5NSZ0eHQtYWxpZ249bGVmdCUyQ3RvcCZ0eHQtY29sb3I9JTIzMUUyMTIxJnR4dC1mb250PUhpcmFnaW5vJTIwU2FucyUyMFc2JnR4dC1zaXplPTU2JnM9MTg4MmM2OTMwN2FjYTdmNTc1YWM2ZTZlMmFlNDUzZTM%26mark-x%3D142%26mark-y%3D57%26blend64%3DaHR0cHM6Ly9xaWl0YS11c2VyLWNvbnRlbnRzLmltZ2l4Lm5ldC9-dGV4dD9peGxpYj1yYi00LjAuMCZoPTc2Jnc9NzcwJnR4dD0lNDBlY29ub21pc3QmdHh0LWNvbG9yPSUyMzFFMjEyMSZ0eHQtZm9udD1IaXJhZ2lubyUyMFNhbnMlMjBXNiZ0eHQtc2l6ZT0zNiZ0eHQtYWxpZ249bGVmdCUyQ3RvcCZzPTczMWViMzdkZDRhY2I1NGI5YzdhN2ExMWYzZWMxMjE4%26blend-x%3D142%26blend-y%3D486%26blend-mode%3Dnormal%26s%3Ddc112929ef7e9d37acaac1f25c91688a)