Dev/JavaScript30

22. Following Along Link Highlight ( JavaScript30 )

takeU 2021. 7. 10. 20:40
반응형

 

Follow Along Link Highlighter

목표

표시해놓은 링크에 포인터가 올라가면 효과를 주는 방법을 알아봄.

 

기본 코드

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>👀👀👀Follow Along Nav</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>

    <nav>
      <ul class="menu">
        <li><a href="">Home</a></li>
        <li><a href="">Order Status</a></li>
        <li><a href="">Tweets</a></li>
        <li><a href="">Read Our History</a></li>
        <li><a href="">Contact Us</a></li>
      </ul>
    </nav>

    <div class="wrapper">
      <p>Lorem ipsum dolor sit amet, <a href="">consectetur</a> adipisicing elit. Est <a href="">explicabo</a> unde natus necessitatibus esse obcaecati distinctio, aut itaque, qui vitae!</p>
      <p>Aspernatur sapiente quae sint <a href="">soluta</a> modi, atque praesentium laborum pariatur earum <a href="">quaerat</a> cupiditate consequuntur facilis ullam dignissimos, aperiam quam veniam.</p>
      <p>Cum ipsam quod, incidunt sit ex <a href="">tempore</a> placeat maxime <a href="">corrupti</a> possimus <a href="">veritatis</a> ipsum fugit recusandae est doloremque? Hic, <a href="">quibusdam</a>, nulla.</p>
      <p>Esse quibusdam, ad, ducimus cupiditate <a href="">nulla</a>, quae magni odit <a href="">totam</a> ut consequatur eveniet sunt quam provident sapiente dicta neque quod.</p>
  <script>
  </script>
</body>
</html>

 

과정

  1. 상수, 태그 생성
  2. 효과 적용을 위한 함수 생성
  3. 효과 적용

 

코드 분석

1. 상수, 태그 생성

const triggers = document.querySelectorAll('a');
const hightlight = document.createElement('span');
highlight.classList.add('highlight');
document.body.appendChild(highlight);

a태그를 triggers에 담고. highlight로 새로운 span태그를 만들어 highlight클래스를 붙여 body의 최하단에 붙임.

2. 효과 적용을 위한 함수 생성

const highlightLink = e => {
    const linkCoords = e.target.getBoundingClientRect();

  const coords = {
    width: linkCoords.width,
    height: linkCoords.height,
    top: linkCoords.top + window.scrollYm
    left: linkCoords.left + window.scrollX
  };
  highlight.style.width = `${coords.width}px`;
  highlight.style.height = `${coords.height}px`;
  highlight.style.transform = `translate(${coords.left}px, ${coords.top}px)`;
}

coords로 현재 태그의 길이,높이, 좌표값을 알아 낸 후에 highlight 클래스에 적용된 효과를 그대로 적용해줌.

3. 효과 적용

triggers.forEach(a => a.addEventListener('mouseenter', hightlightLink));

각각의 a태그에 대해 마우스가 올라갔을 때 highlightLink를 실행

 

찾아본 내용, 알게된 내용들

getBoundingClientRect() - 요소의 사이즈를 설정하는 함수