๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ

์นดํ…Œ๊ณ ๋ฆฌ ์—†์Œ

๋งˆ์šฐ์Šค ์ด๋ฏธ์ง€, ๋”ฐ๋ผ๋‹ค๋‹ˆ๋Š” ๋ผ์ธ, position ํ‘œ๊ธฐํ•˜๊ธฐ

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
๋ฐ˜์‘ํ˜•