์ข
๋ฅ: touchstart
, touchmove
, touchend
๋ฑ์ด ์๋ค. ๋ง์ฐ์ค ์ด๋ฒคํธ์ mousedown, mousemove, mouseup๊ณผ ์ ์ฌํ๋ค.
ํฐ์น ๊ฐ๋ฅํ ๊ธฐ๊ธฐ์์๋ง ํฐ์น ์ด๋ฒคํธ๋ฅผ ํ์ธํ ์ ์๋ค.
๋ฐ์คํฌํ์์ touch ์ด๋ฒคํธ ๊ฐ์ฒด๋ฅผ ์ฝ์์ ์ฐ์ด๋ด๋ ์๋ฌด๋ฐ ๊ฒฐ๊ณผ๊ฐ ๋ํ๋์ง ์๋๋ค. ๋ชจ๋ฐ์ผ ๊ธฐ๊ธฐ๋ก ์ ํํด์ผ ์ฝ์๊ฐ์ ํ์ธํ ์ ์๋ค. (๊ฐ๋ฐ์๋๊ตฌ-toggle device toolbar)
touches
: ํ์ฌ ์คํฌ๋ฆฐ์์ ํฐ์น๋๊ณ ์๋ ๋ชจ๋ ์ง์ ์ ๋ฐํtargetTouches
: ํ์ฌ ํ๊ฒ ๋ด์์ ํฐ์น๋๊ณ ์๋ ์ง์ ๋ค์ ๋ฐํchangedTouches
: ์ด์ ํฐ์น ์ด๋ฒคํธ์ ๋น๊ตํ์ฌ ๋ฌ๋ผ์ง ํฐ์น ํฌ์ธํธ๋ค์ ๋ฐํcontainer.addEventListener("touchstart", (e) => {
console.log("Touches", e.touches.length);
console.log("Target Touches", e.targetTouches.length);
console.log("Changed Touches", e.changedTouches.length);
});
event ๊ฐ์ฒด์ changedTouches
๋ฅผ ๋ฐ์ spread ์ฐ์ฐ์๋ฅผ ํตํด ๋ฐฐ์ด๋ก ๋ณํํ ํ(changedTouches๋ object์ด๊ธฐ ๋๋ฌธ์) forEach๋ฌธ์ ํตํด ์๋ก์ด ํฐ์น ํฌ์ธํธ ๊ฐ์๋งํผ ๋นจ๊ฐ์ ์ ์์ฑํ๋ค. pageX
, pageY
์์ฑ์ ์ด์ฉํ์ฌ ๋นจ๊ฐ์ ์ ์์น๋ฅผ ์ก์์ฃผ๊ณ , ํฐ์นํฌ์ธํธ ์๋ณ๊ฐ์ธ identifier
์์ฑ์ ์ด์ฉํ์ฌ ๋นจ๊ฐ์ ์ id๋ก ์ง์ ํ๋ค.
document.addEventListener("touchstart", (e) => {
[...e.changedTouches].forEach((touch) => {
// ๋นจ๊ฐ์ ์์ฑ
const dot = document.createElement("div");
dot.classList.add("dot");
// ์์น ์ก๊ธฐ
dot.style.top = `${touch.pageY}px`;
dot.style.left = `${touch.pageX}px`;
// id ์ง์
dot.id = touch.identifier;
// DOM์ ์ถ๊ฐ
document.body.append(dot);
});
});
ํฐ์น๊ฐ ๋๋๋ฉด identifier ๊ฐ์ ํ์ฉํ์ฌ ๋นจ๊ฐ์ ์ ์ ํํ๊ณ DOM์์ ์ ๊ฑฐํ๋ค.
document.addEventListener("touchend", (e) => {
[...e.changedTouches].forEach((touch) => {
const dot = document.getElementById(touch.identifier);
dot.remove();
});
});
identifier๋ฅผ ํตํด ๋นจ๊ฐ์ ์ ์ ํํ๊ณ , pageY, pageX ๊ฐ์ ์ด์ฉํ์ฌ ์ ์ ์์น๋ฅผ ์กฐ์ ํ๋ค.
document.addEventListener("touchmove", (e) => {
[...e.changedTouches].forEach((touch) => {
const dot = document.getElementById(touch.identifier);
dot.style.top = `${touch.pageY}px`;
dot.style.left = `${touch.pageX}px`;
});
});
๋ฒ๊ทธ, ์ค๋ฅ ๋ฑ์ผ๋ก ํฐ์น๊ฐ ๋น์ ์์ ์ผ๋ก ์ข ๋ฃ๋ ๋ touchcancel ์ด๋ฒคํธ๊ฐ ์คํ๋๋ค.
document.addEventListener("touchcancel", (e) => {
[...e.changedTouches].forEach((touch) => {
const dot = document.getElementById(touch.identifier);
dot.remove();
});
});
touchstart
์ด๋ฒคํธ์์ e.preventDefault()
๋ฅผ ํธ์ถํ๋ฉด ํฐ์น ๊ธฐ๋ฐ ์ ์ค์ฒ๋ค์ด ๋์ด์ ์คํ๋์ง ์๋๋ค. ๋๋ CSS์์ touch-action
์์ฑ์ none
์ผ๋ก ์ง์ ํด๋ ๋์ผํ ํจ๊ณผ๋ฅผ ๋ผ ์ ์๋ค.
container.addEventListener("touchstart", (e) => {
e.preventDefault();
});