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();
});
관련 글
2012/09/11 - [Dev. 웹/JavaScript/jQuery] - jquery 기초 정리 및 예제
2014/12/04 - [Dev. 웹/JavaScript/jQuery] - [ jQuery 핵심정리 ] DOM 조작 메서드
2015/05/26 - [Dev. 웹/JavaScript/jQuery] - jQuery element 아름답게 생성하기
2016/01/25 - [Dev. 웹/Front-end 웹개발을 위한 codepen] - [2016.1.25] jquery plugin - 단축키 생성 ( easyHotkey )
2014/01/02 - [Dev. 웹/JavaScript/jQuery] - [JQuery 팁] $.css('height') 와 $.height() 의 차이와 활용
2014/04/03 - [Dev. 웹/JavaScript/jQuery] - [jQuery 팁] keyup 바인딩과 focus 함수의 사용 오류
2016/01/27 - [IT 밑거름] - [Front-end tools] 프론트엔드 개발 기술/툴 정리
2016/01/26 - [나에게 쓰는 편지..] - 최근 관심있어지는 Front-end 기술들...
간단한 사용 예제 및 Demo
See the Pen go to next section with arrows by ioannis pelelis (@gpelelis) on CodePen.
'Dev. 웹 > Front-end 웹개발을 위한 codepen' 카테고리의 다른 글
[2016.08.22] input typing 효과 (0) | 2016.08.22 |
---|---|
[2016.4.27] before / after 실시간 전환 이미지 뷰어 (0) | 2016.04.26 |
[2016.2.1] jade, scss, jquery 이용 - css3 keyframe을 활용한 버튼 클릭 애니메이션 (0) | 2016.02.01 |
[2016.1.25] jquery plugin - 단축키 생성 ( easyHotkey ) (0) | 2016.01.25 |
[2016.1.19] flexbox 속성 사용 예제 - direction, align, wrap, justify, grow, shrink, order (0) | 2016.01.19 |