Javascript & JQuery & CSS > $(document), $(window) - scrollTop(), width(), height() - 자동 스크롤 기능
등록일 : 2017-07-14 16:44
조회수 : 259,412
마우스 스크롤을 끝까지 내리면 스크롤을 감지 하거나 (더보기 기능)
마우스 스크롤을 내리다가 배너가 멈춘다거나...
"문제는 사용자가 스크롤을 아래까지 내렸을 때" 이벤트를 캐치하는 것
여기에서 마우스 브라우저 창의 스크롤 끝을 알아낼때..
하나 궁금한점이 있었다.
$(window) vs $(document) 의 차이..
(테스트1)
//width고정 height 100%
html { width: 1000px; height:100%; }
console.log($(window).width()); //364
console.log($(document).width()); //1000
console.log($(window).height()); //441
console.log($(document).height()); //441
윈도우와 도큐먼트는 계속 같아진다.
(테스트2)
//width 고정, height 고정
html { width: 1000px; height:1000px; }
console.log($(window).width()); //364
console.log($(document).width()); //1000
console.log($(window).height()); //441
console.log($(document).height()); //1000
윈도우와 도큐먼트는 css에 따라 고정이 된다.
위와같이 보면 css에서 height를 px이냐 %이냐 따라 달라진다.
var scroll = $(window).scrollTop(); //스크롤의 현재 위치
var docHeight = $(document).height() //도큐먼트 높이로 고정
var winHeight = $(window).height() //윈도우창 높이 가변
console.log(scroll) //1743
console.log(docHeight) //2455
console.log(winHeight)//2546
document = 문서 기준..문서는 코딩에따라서 달라지므로 계속 고정
window = 브라우저창 기준 인거 같음 - 창사이즈가 계속 달라짐.
창사이즈가 줄어들수록 window값은 달라짐.
결론은...
스크롤의 맨마지막 top값을 알려면.
문서높이 - 브라우저창높이 = 스크롤 스크롤 창 끝
$(window).scrollTop() == $(document).height() - $(window).height()
트위터 등과 같은 자동 더 보기 기능을 구현 할려면 아래처럼 하면 되겠다....
$(document).ready(function() {
$(window).scroll(function() {
if ($(window).scrollTop() == $(document).height() - $(window).height())
{
lastPostFunc();
}
});
});
function lastPostFunc()
{
$('div#lastPostsLoader').html('마지막 입니다.............');
};