javascriptでボールを動かす(コピペ)





デモ


デモ


index.html


index.html
<!DOCTYPE html>
<html lang="ja">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title></title>
  </head>
  <body>
    <div
      id="maru"
      style="background: red; width: 50px; height: 50px;border-radius: 50%;"
    ></div>

    <script>
      // 物体をドラック&ドロップできるようにする関数
      const func = obj => {
        obj.style.position = 'absolute';
        obj.style.cursor = 'pointer';
        obj.style.zIndex = '2';

        obj.ondragstart = e => {
          return false;
        };

        const onMouseMove = event => {
          const x = event.clientX;
          const y = event.clientY;
          const width = obj.offsetWidth;
          const height = obj.offsetHeight;
          obj.style.top = y - height / 2 + 'px';
          obj.style.left = x - width / 2 + 'px';
        };

        obj.onmousedown = event => {
          document.addEventListener('mousemove', onMouseMove);
        };

        obj.onmouseup = event => {
          const x = event.clientX;
          const y = event.clientY;
          const width = obj.offsetWidth;
          const height = obj.offsetHeight;
          document.removeEventListener('mousemove', onMouseMove);
        };
      };

      // イベント登録
      func(document.getElementById('maru'));
    </script>
  </body>
</html>



ホームへ