jquery 現在のマウスがある座標を取得する

jquery 現在のマウスがある座標を取得する

jqueryで、現在のマウスがある座標を取得するサンプルコードを記述してます。「mousemove」を使用してます。

環境

  • OS windows10 pro 64bit
  • jquery 3.6.0
  • Apache 2.4.43
  • ブラウザ chrome 91.0.4472.77

現在のマウスがある座標を取得

現在のマウスがある座標を取得するには「mousemove」を使用します。

以下は、マウスを動かすと、移動のイベントをバインドして座標を表示するだけのサンプルコードを記述してます。

※デザインは「semantic-ui」を使用してます。

<!DOCTYPE html>
<html lang="ja">

<head>
  <meta charset="utf-8">
  <title>mebeeサンプル</title>
  <!-- semantic.css  -->
  <link rel="stylesheet" type="text/css"
    href="https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.4.1/semantic.min.css">
  <script src="http://code.jquery.com/jquery-3.6.0.min.js"></script>

</head>
<style>
  body>.grid {
    height: 100%;
  }

  .fields {
    margin-top: 5px;
  }

</style>
<script>

$(function() {

  $(this).mousemove(function() {

    $('#resultx').text(`x座標の位置${event.clientX}`);
    $('#resulty').text(`y座標の位置${event.clientY}`);

  })

})

</script>

<body>

  <div class="ui middle aligned center aligned grid">

    <div class="column">

      <h2 id="resultx" class="ui teal header"></h2>
      <h2 id="resulty" class="ui teal header"></h2>

    </div>
  </div>
</body>

</html>

座標が表示されていることが確認できます。