상세 컨텐츠

본문 제목

[Javascript] 22. Follow Along Link Highlighter

Experience/[Javascript] JS 30

by winCow 2021. 5. 5. 00:27

본문

1. 배경

21은 MacOS나 IOS 환경을 준비할 수 없는 탓에 코드의 정상 작동 여부를 확인할 방법이 없으므로 생략하였다.

미리 지정해 둔 특정한 단어에 마우스를 가져가면 해당 단어를 강조해 주는 기능이다.

 

2. HTML

<!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>
      <p>Aliquam <a href="">dicta</a> sequi culpa fugiat <a href="">consequuntur</a> pariatur optio ad minima, maxime <a href="">odio</a>, distinctio magni impedit tempore enim repellendus <a href="">repudiandae</a> quas!</p>
    </div>

</body>
</html>

 

 

3. CSS

html {
  box-sizing: border-box;
}

*, *:before, *:after {
  box-sizing: inherit;
}

body {
  min-height: 100vh;
  margin: 0; /* Important! */
  font-family: sans-serif;
  background:
    linear-gradient(45deg, hsla(340, 100%, 55%, 1) 0%, hsla(340, 100%, 55%, 0) 70%),
    linear-gradient(135deg, hsla(225, 95%, 50%, 1) 10%, hsla(225, 95%, 50%, 0) 80%),
    linear-gradient(225deg, hsla(140, 90%, 50%, 1) 10%, hsla(140, 90%, 50%, 0) 80%),
    linear-gradient(315deg, hsla(35, 95%, 55%, 1) 100%, hsla(35, 95%, 55%, 0) 70%);
}

.wrapper {
  margin: 0 auto;
  max-width: 500px;
  font-size: 20px;
  line-height: 2;
  position: relative;
}

a {
  text-decoration: none;
  color: black;
  background: rgba(0,0,0,0.05);
  border-radius: 20px;
}

.highlight {
  transition: all 0.2s;
  border-bottom: 2px solid white;
  position: absolute;
  top: 0;
  background: white;
  left: 0;
  z-index: -1;
  border-radius: 20px;
  display: block;
  box-shadow: 0 0 10px rgba(0,0,0,0.2);
}

.menu {
  padding: 0;
  display: flex;
  list-style: none;
  justify-content: center;
  margin:100px 0;
}

.menu a {
  display: inline-block;
  padding: 5px;
  margin: 0 20px;
  color: black;
}

 

 

4. Javascript

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

    function highlightLink() {
      const linkCoords = this.getBoundingClientRect();
      const coords = {
        width: linkCoords.width,
        height: linkCoords.height,
        top: linkCoords.top + window.scrollY,
        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)`;
    }

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

하이라이트를 받을 대상인 HTML의 a 태그들을 triggers로 설정하고, 마우스의 움직임에 맞추어 클래스명이 highlight인 스타일을 적용시킨 빈 span 태그를 생성하여 연결시키는 방법으로 하이라이트 효과를 줄 것이다. 모든 trigger에 각각 mouseenter 이벤트에 반응하여 highlightLink를 실행시키는 이벤트 리스너를 적용한다. mouseenter 이벤트는 마우스 포인터가 이벤트가 발생하는 요소 내에 처음으로 들어갈 때 발생한다.

함수 highlightLink는 마우스 포인터가 요소 내에 들어가면 getBoundingClientRect로 this, 즉 이벤트가 발생한 a태그의 DOMRect를 linkCoords에 할당한다. DOMRect에는 bottom, height, left, right, top, width, x, y에 대한 정보가 담겨 있다.

또, coords 객체를 선언하여, linkCoords의 width, height를 각각 width, height 키의 밸류로, linkCoords의 top과 left에 x, y 스크롤 값을 더하여 top, left 키의 밸류로 할당한다. 이들을 highlight의 스타일 값으로 입력하면, 선택된 a 태그를 따라 같은 크기의 span 태그가 highlight 스타일로 나타나게 된다.

 

※ 그림에서 확인할 수 있듯이, left == x, top == y이다.

 

 

 

'Experience > [Javascript] JS 30' 카테고리의 다른 글

[Javascript] 24. Sticky Nav  (0) 2021.05.07
[Javascript] 23. Speech Synthesis  (0) 2021.05.06
[Javascript] 20. Speech Detection  (0) 2021.05.04
[Javascript] 19. Webcam Fun  (0) 2021.05.03
[Javascript] 18. Adding Up Times with Reduce  (0) 2021.05.01

관련글 더보기

댓글 영역