본문 바로가기
study/JavaScript

project - hover animation(텍스트에 마우스 올리면 배경이 이미지로 바뀜)

by Elfen Lied 2020. 6. 5.
반응형

- HTML -

<body>
    <div class="bg"></div>
    <div class="container">
        <h1>Hover over the links</h1>
        But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I
        will <a data-bg="https://s3-us-west-2.amazonaws.com/s.cdpn.io/485050/freedom.jpg"
        href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/485050/freedom.jpg" target="_blank">freedom</a> you a
        account of the system, and expound the actual teachings of the great of the truth, <a
        data-bg="https://s3-us-west-2.amazonaws.com/s.cdpn.io/485050/travel.jpg"
        href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/485050/travel.jpg" target='_blank'>travel</a>
        master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is, but <a
        data-bg="https://s3-us-west-2.amazonaws.com/s.cdpn.io/485050/explore.jpg"
        href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/485050/explore.jpg" target="_blank">explore</a> those who
        do not know how to pursue pleasure rationally encounter consequences that are <a
        data-bg="https://s3-us-west-2.amazonaws.com/s.cdpn.io/485050/holiday.jpg"
        href="https://s3-us-west-2.amazonaws.com/s.cdpn.io/485050/holiday.jpg" target="_blank">holidays</a> painful.
    </div>
</body>
  1. 웹에서 a태그 내용에 마우스를 올렸을 때 <body>에 클래스명이 추가, 제거 되면서 효과가 발생한다.
  2. <div class="bg"></bg>에 이미지를 담아 a태그 내용에 마우스를 올리거나 내리면 배경화면이 전환되면서
    이미지가 나타나게 한다.

 

 

 

- CSS -

/* RESET RULES
–––––––––––––––––––––––––––––––––––––––––––––––––– */
:root {
--red: firebrick;
--white: white;
}

* {
padding: 0;
margin: 0;
}

a {
color: inherit;
text-decoration: none;
}

body {
font: 22px/1.5 sans-serif;
}

h1 {
text-align: center;
margin: 20px 0;
}


/* MAIN STYLES
–––––––––––––––––––––––––––––––––––––––––––––––––– */
.container {
    max-width: 800px;
    margin: 0 auto;
    width: 100%;
}
.container a {
    border-bottom: 2px dashed var(--red);
    position: relative;
}
.container a:before {
    content:'';
    position: absolute;
    top: 50%;
    left: 50%;
    width: 100%;
    height: 100%;
    min-height: 30px;
    transform: translate(-50%, -50%) scaleX(0);
    padding: 10px;
    z-index: -1;
    transform-origin: 50% 50%;
    background: var(--white);
    transition: all 0.3 ease-out;
}
.bg {
    position: absolute;
    left: 0; right: 0; top: 0; bottom: 0;
    opacity: 0;
    background-repeat: no-repeat;
    background-position: center;
    background-size: cover;
    transition: all 0.3s ease-out;
}
.bg-show .bg {  // javascript에서 body에 추가한 클래스(bg-show)
    opacity: 1;
    z-index: 1;
}
.container a:hover {
    z-index: 2;
    border-bottom-color: transparent;
    color: var(--red);
    background: wihte;
}
.container a:hover:before {
    transform: translate(-50%, -50%) scaleX(1);
}
  1. .container a에 보더바텀을 2px의 dashed 점선에 red
  2. 이때 var(--red);는 css 가장 위쪽에 root에 지정되어 있다.
  3. 사용자 지정 속성을 사용해서 한 영역에 값을 저장해놓고, 다른 공간에서 참조해갈 수 있다.
  4. .container a:hover 했을때 보더 바텀을 투명하게 하고 글자색을 지정한 --red로 한다 그리고 a의 배경색을 white로 바뀌고 z-index를 2로한다. 2로 하는 이유는 bg-show에서 이미지가 z-index 1이 되기때문에 그보다 위에 있어야한다.

 

 

 

 

 

- JAVASCRIPT -

window.onload = function () {

    const links = document.querySelectorAll('.container a');
    const bg = document.querySelector('.bg');
    const showClass = 'bg-show';   //body에 클래스 추가

    for (const link of links) {   //link of links 는 상수 links를 link으로 하나하나 명명하겠다라는 것
        const img = new Image();
        img.src = link.dataset.bg;   // link는(const links)에 data-bg(img 주소를 가져온다. HTML 확인)
        
        link.addEventListener('mouseenter', function () {
            bg.style.backgroundImage = `url(${this.dataset.bg})`;  //마우스가 link(a)에 들어가면 css스타일에 배경이미지를 가져온다.
            document.body.classList.add(showClass);             // 그리고 body에 클래스 bg-show를 추가함 (const showClass)
        });
        
        link.addEventListener('mouseleave', function () {
            document.body.classList.remove(showClass);      // 마우스가 link(a)에서 벗어나면 body에 클래스(bg-show) 지운다
        });

    }

}

 

  1.  각각의 변수를 지정. 이때는 const를 사용했음 (const는 상수로써 값이 바뀌지 않는다)
  2. for (const link of links) 는 links를 반복하고 정의한 link로 호출한다.
  3.  const img로 src에 주소를 담아준다. link.dataset.bg (<a data-bg="http://이미지주소"></a>)
  4. console.log(img); 콘솔로그를 써서 잘 담겼는지 확인을 해볼것.
  5. 마우스를 올리거나 빠졌을때 할일을 만들어준다. addEventListener (mouseenter 와 mouseleave)
  6. 마우스를 올렸을때 (mouseenter) bg.style.backgroundImage = `url(${this.dataset.bg})`;
  7. document.body.classList.add(showClass);
  8. 즉, class명 bg의 css스타일을 바꿔주는데 배경이미지를 다음 주소로 가지고 오고,
  9. 또, document문서의 body에 classList에 add(showClass)추가한다 (showClass)는 변수로 선언했음.
  10. 마우스가 빠졌을때 (mouseleave) document.body.classList.remove(showClass);
  11. 위와 같이 body의 클래스명을 바꿔주는데 이번엔 remove 즉 class를 제거하는 것이다.
  12. 마우스를 올리거나 빠질때 body에 클래스명 bg-show를 추가하고 제거하는건 조건에 따라 CSS를 적용하기 위함임.

 

 

 

반응형

'study > JavaScript' 카테고리의 다른 글

함수 객체  (0) 2020.05.25
Event - click 이벤트, mouseenter, mouseleave 이벤트  (0) 2020.05.10
스타일 변경하기  (0) 2020.05.10
선택자  (0) 2020.05.10
문자열 추출, 합치기 , 타이머 설정  (0) 2020.05.09

댓글