Back to the JavaScript
무한 스크롤 / window.onscroll( )
Backcoder
2022. 8. 5. 21:23
무한으로 append 할 글씨
var appendDocument = function () {
for (var i = 0; i < 20; i++) {
// $('<h1>Infinity Scroll</h1>').appendTo('body');
$('body').append('<h1>Infinity Scroll</h1>');
}
};
appendDocument();
< JS 버전 스크롤에 이벤트 >
window.onscroll = function(){}
=> 스크롤하면 함수 실행
< jquery 버전 >
$(window).scroll ( function(){ } )
$(window).scroll(function () {
//스크롤이전가려진부분 높이 + 현재뷰포트높이
var scrollHeight = $(window).scrollTop() + $(window).height();
var documentHeight = $(document).height();//문서높이
if (scrollHeight == documentHeight) {
appendDocument();
}
=> 스크롤 이벤트가 발생할 때,만약 전체 doc 길이 == 현재뷰포트길이 + 위에 길이 가 같아지면
( 즉 전체 doc 길이가 위에서 부터 쓴 글씨 길이로 꽉 차면 )
=>또 20개 추가해라
=> 무한스크롤
document.height( ) 문서 전체 높이 =
window.scrollTop( ) 위에 안보이는 스크롤 높이 +
window.height( ) 현재 뷰포트 높이
이 높이들을 사용해서
window.onscroll 이벤트를 걸어두면 무한 스크롤이 구현된다.