マウス・タッチイベントが発生した座標を取得する
ウィンドウ内 / 要素内 / ディスプレイ上
もくじ
ページ内でのイベント発生座標
pageX
/pageY
を使う。この値にはスクロール分も含まれるので、ウィンドウ内での座標が欲しい場合は次項。
// マウス
document.getElementById('foo').addEventListener('mousemove', function (e) {
console.log(`ページ内で... x=${e.pageX}, y=${e.pageY}`);
});
// タッチ
document.getElementById('bar').addEventListener('touchmove', function (e) {
for (let i = 0; i < e.changedTouches.length; ++i) {
const touch = e.changedTouches[i];
console.log(`ページ内で... x=${touch.pageX}, y=${touch.pageY}`);
}
});
ウィンドウ内でのイベント発生座標
pageX
/pageY
から window.scrollX
/window.scrollY
を引くことで、ウィンドウ内での座標を算出できる。
// マウス
document.getElementById('foo').addEventListener('mousemove', function (e) {
const windowX = e.pageX - window.scrollX;
const windowY = e.pageY - window.scrollY;
console.log(`ウィンドウ内で... x=${e.windowX}, y=${e.windowX}`);
});
// タッチ
document.getElementById('bar').addEventListener('touchmove', function (e) {
for (let i = 0; i < e.changedTouches.length; ++i) {
const touch = e.changedTouches[i];
const windowX = touch.pageX - window.scrollX;
const windowY = touch.pageY - window.scrollY;
console.log(`ウィンドウ内で... x=${touch.pageX}, y=${touch.pageY}`);
}
});
要素内でのイベント発生座標
イベントの clientX
/clientY
と、要素の getBoundingClientRect()
で取得した left
/top
で算出できる。
// マウス
document.getElementById('foo').addEventListener('mousemove', function (e) {
const bounds = e.currentTarget.getBoundingClientRect();
const x = e.clientX - bounds.left;
const y = e.clientY - bounds.top;
console.log(`要素内で... x=${e.pageX}, y=${e.pageY}`);
});
// タッチ
document.getElementById('bar').addEventListener('touchmove', function (e) {
for (let i = 0; i < e.changedTouches.length; ++i) {
const touch = e.changedTouches[i];
const bounds = touch.target.getBoundingClientRect();
const x = touch.clientX - bounds.left;
const y = touch.clientY - bounds.top;
console.log(`要素内で... x=${x}, y=${y}`);
}
});
ディスプレイ上でのイベント発生座標
screenX
/screenY
を使う。
マルチディスプレイで画面を拡張している場合はその分も含まれているので、ウィンドウ内の座標を取得する目的で使わないよう注意。
// マウス
document.getElementById('foo').addEventListener('mousemove', function (e) {
console.log(`ディスプレイ上で... x=${e.screenX}, y=${e.screenY}`);
});
// タッチ
document.getElementById('bar').addEventListener('touchmove', function (e) {
for (let i = 0; i < e.changedTouches.length; ++i) {
const touch = e.changedTouches[i];
console.log(`ディスプレイ上で... x=${touch.screenX}, y=${touch.screenY}`);
}
});