반응형
기본 코드
<!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>
<script>
</script>
</body>
</html>
목표
주요 단어들에 마우스가 올라가면 highlight
가 되도록 만들어보자.
기본 코드
const triggers = document.querySelectorAll('a');
const highlight = document.createElement('span');
highlight.classList.add('highlight');
document.body.appendChild(highlight);
function highlightLink() {
const linkCoords = this.getBoundingClientRect();
console.log(linkCoords);
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));
먼저 사용할 변수들에 대해서 선언한 다음.appendChild
를 사용하여 body
에 highlight
를 추가해준다..getBoundingClientRect()
는 그 엘리먼트의 크기와 뷰 포트에서의 상대적인 위치값을 리턴해주는 메서드이다.
따라서 이 메서드를 통해 사용할 위치변수에 대해 정의해 놓는다.
그런데 top
과 left
에 scrollY
와 scrollX
를 추가해준 이유는 스크롤을 내리게 되면 뷰 포트에서의 상대적인 위치값은 그대로인데 스크롤이 내려가버려서 원하는 위치에 highlight
를 줄수가 없기 때문이다.
그리고 그 다음 아래 내용은 highlight
의 가장자리 범위를 정해주고, 마우스가 가리키는 곳에서 highlight
되도록 위치를 변경해주는 것을 지정해 준 것이다.
마무리
.getBoundingCliengRect()
라는 메서드를 처음 알았고 이를 이용해서 효과를 적용하는 것도 새로웠다.
끝.
반응형
'개발 > JavaScript 30' 카테고리의 다른 글
24. Sticky Nav (0) | 2017.04.26 |
---|---|
23. Speech Synthesis (0) | 2017.04.26 |
21. Geolocation (0) | 2017.04.26 |
20. Speech Detection (0) | 2017.04.24 |
19. Webcam Fun (0) | 2017.04.24 |