728x90

์ค๋๋ง์ ๋ณต์ตํ๋ ๋ง์ด ๊น๋จน์๋ค.
๊ทธ๋๋ ๊ฒ์ํด์ ์์ฑ์ํด!
1. ๋จผ์ ์ขํ text, ๋ผ์ธ(div) ์์ฑ
2. JS์์ addEventListener๋ฅผ ์ด์ฉํด ๋ง์ฐ์ค๊ฐ ์์ง์ด๋ ์์น๋ฅผ positionX, positionY ๋ก ๋ฐ์์จ ํ
3. ์ด๊ฑธ line์ position์ (top, left ) ์ ์ฉ์ํด.
4. ์ขํ์ innerText๋ก ์ญ์ pageX, pageY๋ฅผ ๋ฐ์์ํด.
5. ๋ง์ฐ์ค์ ์์น ์ฝ๊ฐ ์๋(20px์ฉ) ์ text ์์น๋ฅผ ๋ฐ์์ํด.
5. text, line์ position์ ๋ชจ๋ relative๋ฅผ ์ ์ฉ์ํด.
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Coordinates</title>
<script src="main.js" defer></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class='coordinates'>
<span id='x'>0px</span>
<span id='y'>0px</span>
</div>
<div class='x-line'></div>
<div class='y-line'></div>
</body>
</html>
css
* {
cursor: url(img/target.png) 51 30, auto;
background-color: black;
color: whitesmoke;
}
body {
position: relative;
width: 100%;
height: 100vh;
}
.x-line {
width: 100%;
height: 1px;
}
.y-line {
width: 1px;
height: 100vh;
}
.x-line,
.y-line {
background-color: whitesmoke;
position: relative;
}
.coordinates {
position: relative;
}
JS
const x = document.getElementById("x");
const y = document.getElementById("y");
const xLine = document.querySelector(".x-line");
const yLine = document.querySelector(".y-line");
const text = document.querySelector(".coordinates");
const handleMouseMove = (event) => {
const xPosition = event.pageX;
const yPosition = event.pageY;
x.innerText = `${xPosition}px`;
y.innerText = `${yPosition}px`;
xLine.style.top = `${yPosition}px`;
yLine.style.left = `${xPosition}px`;
text.style.top = `${yPosition + 20}px`;
text.style.left = `${xPosition + 20}px`;
}
window.addEventListener("mousemove", handleMouseMove)
+ ๊ฐ์์์ ํ ๋ฐฉ๋ฒ
: mouse์ ์ด๋ฏธ์ง๋ฅผ ๋ฐ๊พธ๋๊ฒ ์๋๋ผ,
html ์์ img ํ๊ทธ๋ก ๋ง์ฐ์ค ์ด๋ฏธ์ง๋ฅผ ๋ฃ์ด์ค๋ค.
position: absolute;
top: 50%;
left: 50%;
tranform: translate(-50%, -50%);
=> ์ ๊ฐ์ด๋ฐ์์ ์ด๋ฏธ์ง์ ์ ๋ฐ๋งํผ ์ค์์ผ๋ก ์ด๋ํจ.
728x90
๋ฐ์ํ