본문 바로가기
Front-end/Javascript 실습

윈도우에서 마우스 커서 좌표 찾기

by warrior.p 2022. 3. 16.

 

업그레이드 버전 (빠른 브라우져 로딩)

https://jsp0422.tistory.com/69?category=974379

 

<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="line horizontal"></div>
    <div class="line vertical"></div>
    <img class="target" src="img/target.png" alt="target" />
    <span class="tag">target</span>
  </body>
</html>

<CSS>

body {
  background-color: black;
}
.line {
  position: absolute;
  background-color: white;
}
.horizontal {
  width: 100%;
  height: 1px;
  top: 50%;
}
.vertical {
  height: 100%;
  width: 1px;
  left: 50%;
}

.target {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.tag {
  color: white;
  position: absolute;
  top: 50%;
  left: 50%;
  font-size: 38px;
  transform: translate(20px, 20px);
}

<Javascript>

const vertical = document.querySelector('.vertical');
const horizontal = document.querySelector('.horizontal');
const target = document.querySelector('.target');
const tag = document.querySelector('.tag');

document.addEventListener('mousemove', event => {
  const x = event.clientX;
  const y = event.clientY;
  console.log(`${x} ${y}`);

  vertical.style.left = `${x}px`;
  horizontal.style.top = `${y}px`;
  target.style.left = `${x}px`;
  target.style.top = `${y}px`;
  tag.style.left = `${x}px`;
  tag.style.top = `${y}px`;
  tag.innerHTML = `${x}px, ${y}px`;
});
  • mosuemove event