[2016.09.02] 화살표키로 문단 이동하기 (jquery) :: 소림사의 홍반장!

jquery의 scrollTop, offset 을 활용하여 화살표키로 한 문단씩 이동하게 만들었네요.


jquery 기초예제라 할 수 있겠습니다.ㅎ




그럼 소스를 살짝 살펴 볼까요~


* JS 영역


var canScrollNext = true;

var canScrollPrev = true;



/**

  * 1. Force an integer return on offset.top even when we have hdpi screen

  * 2. Stop bottom scrolling when we are on bottom of the page

  * 3. Continue top scrolling when we are not on section 1 

  */

var scrollToNext = function(){

  var current_pos = $(window).scrollTop();

  var section = $('.js-sectionGo');

  

  for (var i=0; i<section.length; i++){

    var pos = Math.round($(section[i]).offset().top); /* 1 */

    if (current_pos < pos && canScrollNext){

      $("html, body").animate({

        scrollTop: pos }, 250,

        function(){

          canScrollNext = i == section.length-1 ? false : true; /* 2 */

          canScrollPrev = i > 0 ? true : false; /* 3 */

         });

      break;

    }

  }

}


/**

  * 1. Force an integer return on offset.top even when we have hdpi screen

  * 2. Stop top scrolling when we are on top of the page

  * 3. Continue bottom scrolling when we are not on last section

  */

var scrollToPrev = function(){

  var current_pos = $(window).scrollTop();

  var section = $('.js-sectionGo');

  

  for (var i=section.length-1; i>=0; i--){

    var pos = Math.round($(section[i]).offset().top); /* 1 */

    if (current_pos > pos && canScrollPrev){

      $("html, body").animate({ scrollTop: pos }, 250,

          function(){

            canScrollNext = i < section.length ? true : false; /* 2 */

            canScrollPrev = i == 0 ? false : true;  /* 3 */

          });

      break;

    }

  }

}


$(window).keydown(function(e){

  if (e.which == 38) // up key

    scrollToPrev();

  else if (e.which == 40) // down key

    scrollToNext();

  

  // prevent the default action (scroll / move caret)

  e.preventDefault(); 

});


간단한 사용 예제 및 Demo

See the Pen go to next section with arrows by ioannis pelelis (@gpelelis) on CodePen.


다른 카테고리의 글 목록

Dev. 웹/Front-end 웹개발을 위한 codepen 카테고리의 포스트를 톺아봅니다