본문 바로가기
IT

jQuery와 CSS3에서 손쉽게 구현할 수있는 스크롤 효과

by 왕소라과자 2017. 3. 7.
반응형

최근 Web 디자인 갤러리 사이트에서 볼 수있는 멋진 Web 사이트는, 아무도 애니메이션 등의 효과가 근사 하지요. 그래서 이번 기사는 그 중에서도 쉽게 구현할 수있을 것 같은 효과를 하나. 스크롤하여 요소가 가시 범위에 표시되면 CSS3의 애니메이션을 사용한 효과가 실행된다는 것을 구현하고 보려고합니다. 왠지 어려울 것 ... 그리고 무작정에 있던 사람도 기본 마저 눌러두면 나머지는 생각대로 원하는대로 사용자 정의 할 수 있다고 생각 해요!


화면을 스크롤하면 아래에서 부와 ~ 응과 텍스트가 표시되는 효과를 구현하자!

우선 효과를주는 요소를 HTML로 작성. 안심하십시오, 아직 아무것도 달라진 것은 없습니다.

<p>Nobody likes you</p>

<p>Everyone left you</p>

<p>They're all out without you</p>

<p>Havinng fun</p>


다음 jQuery 를로드합니다. 물론, jQuery 파일을 다운로드하여 이용해도 OK입니다.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>


자바스크립트입니다.

$(window).scrollTop();에서 윈도우 스크롤 위치 (상단)을 가져옵니다. $(this).offset().top;는 p요소의 위치 네요. 그리고, scrollY > elPosition - windowH이 ' p요소가 화면에 나타나면'라는 뜻입니다. 조금 이해하기 어렵 습니다만, 전술대로 취득한 스크롤 위치는 창 상단이므로 p요소의 위치에서 창 높이를 당겨 주면 p요소가 창 하단에 위치하는 타이밍을 얻을 수있는 것은 입니다.


그런 이유로 " p요소가 화면에 나타나면" txt-effect이라는 클래스를 p요소에 달아드립니다.


$(window).scroll(function() {

  var windowH = $(window).height(),

  scrollY = $(window).scrollTop();

 

  $('p').each(function() {

    var elPosition = $(this).offset().top;

    if (scrollY > elPosition - windowH) {

      $(this).addClass("txt-effect");

    }

  });

});


마지막으로 CSS입니다. 기본적으로 불투명도 10 %, 문자 크기 20px 텍스트를 스크롤하여 txt-effect라는 클래스가 추가되면, 불투명도 및 글꼴 크기를 변경합니다.


p {

  text-align: center;

  margin-bottom: 50px;

  font-size: 20px;

  opacity: .1;

}

.txt-effect {

  animation: txtEffect 2s both;

}

@keyframes txtEffect {

  100% {

    opacity: .5;

    font-size: 48px;

  }

}


그러고 보니 최신 브라우저에서는 -webkit-벤더 접두사를 붙이지 않아도 좋아진 때문에 코드가 꽤 깔끔한 했군요.


완성!


html입니다.

<p>Nobody likes you</p>

<p>Everyone left you</p>

<p>They're all out without you</p>

<p>Havinng fun</p>

<p>Everyone left you</p>

<p>Nobody likes you</p>

<p>They're all out without you</p>

<p>Havinng fun</p>

<p>Where'd you go?</p>


스타일입니다.

body {

  padding: 300px 0 100px;

  background: linear-gradient(45deg, #000000 10%, #53346D 90%);

  color: #fff;

}

p {

  text-align: center;

  margin-bottom: 50px;

  font-size: 20px;

  opacity: .1;

}

.txt-effect {

  animation: txtEffect 2s both;

}

@keyframes txtEffect {

  100% {

    opacity: .5;

    font-size: 48px;

  }

}


스크립트입니다.

$(window).scroll(function() {

  var windowH = $(window).height(),

    scrollY = $(window).scrollTop();

  $('p').each(function() {

    var elPosition = $(this).offset().top;

    if (scrollY > elPosition - windowH) {

      $(this).addClass("txt-effect");

    }

  });

});


응용 : 흐림이 걸린 이미지를 선명하게 표시


전부터 Medium 에서 구현되는 처음에는 흐림이 걸린 이미지가 스크롤하여 가볍게 애니메이션을 달아 선명하게 나타나는 효과가 궁금했습니다. 본가는 다른 방식으로 구현하는 거라고 생각 합니다만, 여기에서는 조금의 효과와 마찬가지로 jQuery와 CSS3에서 구현하자.


CSS에서 흐림을 구현하기 위해 filter속성을 이용하고 있습니다. 이것은 현 단계에서는 불행히도 IE에 지원하지 않습니다. 기본적으로 이미지에 15px의 빚을 들여 스크롤의 새로운 클래스가 주어지면 흐림 값을 0으로하여 이미지를 표시합니다.


img {

  -webkit-filter: blur(15px);

  filter: blur(15px);

}

.img-blur {

  animation: imageBlur 1s both;

}

@keyframes imageBlur {

  100% {

    -webkit-filter: blur(0);

    filter: blur(0);

  }

}


완성!


<article>

  <h1>Rapunzel</h1>

  <p>

    Once upon a time there was a man and a woman who had long, but to no avail, wished for a child. Finally the woman came to believe that the good Lord would fulfill her wish. Through the small rear window of these people's house they could see into a splendid garden that was filled with the most beautiful flowers and herbs. The garden was surrounded by a high wall, and no one dared enter, because it belonged to a sorceress who possessed great power and was feared by everyone.

  </p>

  <img src="http://www.webcreatorbox.com/sample/images/garden.jpg" alt="" />

  <p>

    One day the woman was standing at this window, and she saw a bed planted with the most beautiful rapunzel. It looked so fresh and green that she longed for some. It was her greatest desire to eat some of the rapunzel. This desire increased with every day, and not knowing how to get any, she became miserably ill.

  </p>

  <img src="http://www.webcreatorbox.com/sample/images/beach-footprint.jpg" alt="" />

  <p>

    Her husband was frightened, and asked her, "What ails you, dear wife?"

  </p>

  <img src="http://www.webcreatorbox.com/sample/images/demo14-cat.jpg" alt="" />

  <p>

    "Oh," she answered, "if I do not get some rapunzel from the garden behind our house, I shall die."

  </p>

  <img src="http://www.webcreatorbox.com/sample/images/demo9-beach.jpg" alt="" />

  <p>

    The man, who loved her dearly, thought, "Before you let your wife die, you must get her some of the rapunzel, whatever the cost."

  </p>

  <img src="http://www.webcreatorbox.com/sample/images/hands-heart-love.jpg" alt="" />

  <p>

    So just as it was getting dark he climbed over the high wall into the sorceress's garden, hastily dug up a handful of rapunzel, and took it to his wife. She immediately made a salad from it, which she devoured eagerly. It tasted so very good to her that by the next day her desire for more had grown threefold. If she were to have any peace, the man would have to climb into the garden once again. Thus he set forth once again just as it was getting dark. But no sooner than he had climbed over the wall than, to his horror, he saw the sorceress standing there before him.

  </p>

  <img src="http://www.webcreatorbox.com/sample/images/beach.jpg" alt="" />

  <p>

    "How can you dare," she asked with an angry look, "to climb into my garden and like a thief to steal my rapunzel? You will pay for this."

  </p>

  <img src="http://www.webcreatorbox.com/sample/images/rose.jpg" alt="" />

  <p>

    "Oh," he answered, "Let mercy overrule justice. I came to do this out of necessity. My wife saw your rapunzel from our window, and such a longing came over her, that she would die, if she did not get some to eat."

  </p>

</article>


css입니다.

/* GENERAL STYLING */

body {

  font: 18px/1.5 georgia, serif;

}

article {

  width: 600px;

  margin: 0 auto;

}

h1 {

  font-weight: normal;

  text-align: center;

}


/* IMAGE BLUR EFFECT */

img {

  max-width: 600px;

  -webkit-filter: blur(15px);

  filter: blur(15px);

}

.img-blur {

  animation: imageBlur 1s both;

}

@keyframes imageBlur {

  100% {

    -webkit-filter: blur(0);

    filter: blur(0);

  }

}


$(window).scroll(function() {

  var windowH = $(window).height(),

    scrollY = $(window).scrollTop();

  $('img').each(function() {

    var imgPosition = $(this).offset().top;

    if (scrollY > imgPosition - windowH) {

      $(this).addClass("img-blur");

    }

  });

});


위의 방법을 마스터하면 속성을 바꾸는 것만으로 여러가지 표현 방법에 대응할 수 있다고 생각합니다. 예를 들면 width나 height크기를 바꾸거나 색상과 위치, 배경 이미지 변경 transform: rotate에서 빙글 빙글 돌리거나 ... 등등. 너무 너무하면 페이지가 잘 보이지되므로, 콘텐츠 및 디자인에 따라 효과의 정도를 조정 해주세요.

반응형

댓글