티스토리 뷰

*스크롤 이벤트를 일으키는 같은 코드

제이쿼리

$(window).on('scroll', function(){
  console.log(
    $(window).scrollTop()
  );
})

 

바닐라 자바스크립트

window.onscroll = function(){
  console.log(
    window.scrollY
  );
}

window.addEventListener('scroll', function(){
  console.log(
    window.scrollY
  );
})

 

 

스크롤을 내렸는지 올렸는지 알아내기

let scrollPos = {
  y: 0, dy: 0, state: true
}

$(window).on('scroll', function(){
  scrollPos.y = $(window).scrollTop() // {}안의 값을 빼올 때 . 사용!

  if(scrollPos.y > scrollPos.dy){ // dy 값은 처음 할당한 0
    "down"
  }else{
    "up"
  }
  scrollPos.dy = scrollPos.y; // dy 값은 조건문 실행 후에 새롭게 저장됨
})
$(window).on('scroll', function(){
  scrollPos.y = $(window).scrollTop()

  if(scrollPos.y > scrollPos.dy){
    scrollPos.state = true; // down
  }else{
    scrollPos.state = false; // up state에 불리언 값도 할당
  }
  scrollPos.dy = scrollPos.y;
})

 

함수로 묶기

function scrollState() {
  scrollPos.y = $(window).scrollTop()
  if (scrollPos.y > scrollPos.dy) {
    scrollPos.state = true; // down
  } else {
    scrollPos.state = false; // up
  }
  scrollPos.dy = scrollPos.y;
}

$(window).on('scroll', function () {
  scrollState();
  console.log(scrollPos.state);
})

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script  src="http://code.jquery.com/jquery-latest.min.js"></script>
  <script defer src="./js/2-3.scroll.js"></script>
  <title>Document</title>
</head>
<body>
  <style>
    header {
      position: fixed;
      left: 0;
      top: 0;
      width: 100%;
      background-color: #000;
      text-align: center;
    }
    header a {
      color: #fff;
      font-size: 2em;
    }
    section {
      height: 120vh;
      display: flex;
      justify-content: center;
      align-items: center;
    }
    section:nth-of-type(odd){
      background-color: #eee;
    }
  </style>
  <header>
    <nav>
      <a href="0">HOME</a>
      <a href="1">SERVICE</a>
      <a href="2">BOARD</a>
    </nav>
    <p><!--라인--></p>
  </header>
  <main>
    <section>content 01</section>
    <section>content 02</section>
    <section>content 03</section>
  </main>
</body>
</html>

 

nav a를 클릭하면 해당 번호의 컨텐츠로 이동

let contentHeight;
let index;

$('header a').on('click', function(e){
  e.preventDefault(); // href 작동 정지

  index = $(this).index();
  contentHeight = $('section').eq(index).offset().top;
  $(window).scrollTop(contentHeight);
})

바닐라 자바스크립트라면 .attr('href')로 값을 가져와서 사용

 

 

 

스크롤링을 부드럽게 하기

CSS : scroll-behavior

scroll-behavior: smooth;

 

.animate() 메소드

window와 document는 불가능

  $('html').animate({
    scrollTop : contentHeight
  });
  $('html').animate({
    scrollTop : contentHeight
  }, 1000, 'easeOutBounce'); // 스피드 설정, 액션 설정

https://api.jqueryui.com/easings/

 

Easings | jQuery UI API Documentation

Easings Easing functions specify the speed at which an animation progresses at different points within the animation. jQuery core ships with two easings: linear, which progresses at a constant pace throughout the animation, and swing (jQuery core's default

api.jqueryui.com

액션은 플러그인을 링크해줘야 사용가능

 

jquery UI 플러그인

<script src="https://code.jquery.com/ui/1.13.0/jquery-ui.js"></script>

 

 

콜백 함수

+

자세히 다루지 않아서 공부해야할듯

  $('html').animate({
    scrollTop : contentHeight
  }, 700, 'easeOutBounce', function(){ // 콜백 함수
    console.log(contentHeight);
  });

 

컨텐츠를 드래그하기

.draggable();

$('선택자').draggable();

$('header').draggable({
  axis: "y", // 움직일 수 있는 축 설정
  revert: true, // 드래그를 끝내면 다시 돌아가도록 설정
  start: function(){console.log('start')}, // 드래그를 시작할 때
  drag: function(){console.log('drag')}, // 드래그 중
  stop: function(){console.log('end')} // 드래그를 끝낼 때
});

드래그해서 넘어가는 슬라이드를 만들 수 있겠죠?!

 revert: function(){
    if($(this).offset().top > ($(window).height()/2)) { // 브라우저의 높이의 1/2보다 많이 움직이면 돌아가지 않음
      return false
    } else { // 브라우저 높이의 1/2보다 적게 움직이면 제자리로 돌아감
      return true
    }
  }

부모 엘리먼트까지만 드래그 할 수 있게 하기

$('header').draggable({
containment: "부모 엘리먼트(tag, class, id)"
})

 

 

 

클릭한 a 태그에 p태그가 이동하도록 하기

    p {
      position: fixed;
      left: 0;
      top: 0;
      border: 2px solid red;
      margin: 0;
      transition: 0.5s;
    }
  $('p').css({
    left: $(this).offset().left,
    top: 0,
    width: $(this).width(),
    height: $(this).height()
  })

이렇게 하면 a태그의 높이를 변경했을 때 다시 설정해줘야함

 

let aTop = $(this).offset().top;

처음에 변수로 선언해주고 이 값을 top이 받아가게 설정

아니면 top값에 컨텐츠들의 위치를 연산한 값을 사용해도 됨

728x90
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/07   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
글 보관함