web関連

【jquery,javascript】”mousemove”と”touchmove”イベントで座標を取得する方法が違う件

PCのマウス座標とスマホのタップをしている位置の座標を取得する時に方法が違くて困惑したので備忘録

“mousemove”と”touchmove”の座標取得方法の違い

jQueryとjavascriptで座標の取得方法と

jQuery

// PCのマウスポインターの座標を取得
$(document).on("mousemove",function(e){
  console.log(e);// n.Event {originalEvent: MouseEvent, type: "mousemove", timeStamp: 2675.329999998212, jQuery214013954162086980282: true, isDefaultPrevented: ƒ, …}
  console.log(e.clientX);// 79
  console.log(e.clientY);// 441
  console.log(event.clientX);// 79
  console.log(event.clientY);// 441
  console.log(event);// MouseEvent {isTrusted: true, screenX: 483, screenY: 543, clientX: 79, clientY: 441, …}
});

// スマホのタップしている時の座標を取得
$(document).on('touchmove', function(e){
  console.log(e);// n.Event {originalEvent: TouchEvent, type: "touchmove", timeStamp: 1108.5600000806153, jQuery214001637072764189562: true, isDefaultPrevented: ƒ, …}
  // console.log(e.changedTouches[0].clientX);// error
  // console.log(e.changedTouches[0].clientY);// error
  console.log(event.changedTouches[0].clientX);// 79
  console.log(event.changedTouches[0].clientY);// 441
  console.log(event);// TouchEvent {isTrusted: true, touches: TouchList, targetTouches: TouchList, changedTouches: TouchList, altKey: false, …}
});

mousemoveの時は引数にeを指定してもeventで座標取得できるけど、touchmoveだとだめだね

引数に設定するとイベントオブジェクトを取得できるし、「e」でも「ev」でもいいって書いてあったりするんだけど「event」でイベント取得できるんだけど、「引数のe=イベントの種類を取得」「event=イベントの種類の中のイベントの詳細を取得」で「event」を使わないで「e」を使うのはそっちのほうが短く書けるから的な意味?

javascript

// PCのマウスポインターの座標を取得
window.addEventListener("mousemove", function(e){
  console.log(e);// MouseEvent {isTrusted: true, screenX: 408, screenY: 175, clientX: 4, clientY: 72, …}
  console.log(e.clientX);// 4
  console.log(e.clientY);// 72
  console.log(event);// MouseEvent {isTrusted: true, screenX: 408, screenY: 175, clientX: 4, clientY: 72, …}
});

// スマホのタップしている時の座標を取得
window.addEventListener("touchmove", function(e){
  console.log(e);// TouchEvent {isTrusted: true, touches: TouchList, targetTouches: TouchList, changedTouches: TouchList, altKey: false, …}
  console.log(e.changedTouches[0].clientX);// 79
  console.log(e.changedTouches[0].clientY);// 441
  console.log(event.changedTouches[0].clientX);// 79
  console.log(event.changedTouches[0].clientY);// 441
  console.log(event);// TouchEvent {isTrusted: true, touches: TouchList, targetTouches: TouchList, changedTouches: TouchList, altKey: false, …}
});

javascriptの時は「e」も「event」も取得できるものは一緒だね

結論

eventという変数?は”mousemove”と”touchmove”どちらも存在しており、jQueryを使った時のみ
引数eeventの値が変わる

参考(読んでおきたい記事)

function(e){…}って書いておいて引数の「e」使わないこともあるみたい
まじでわかんねー

Leave a Comment

入力エリアすべてが必須項目です。メールアドレスが公開されることはありません。

内容をご確認の上、送信してください。