자바 스크립트 : 브라우저 창이 아래로 스크롤되는지 감지하는 방법?


187

사용자가 페이지 하단으로 스크롤되는지 감지해야합니다. 페이지 하단에 새 콘텐츠를 추가하면 자동으로 새 하단으로 스크롤됩니다. 그들이 맨 아래에 있지 않으면 페이지에서 이전 내용을 더 많이 읽으므로 원래 위치에 머무르고 싶기 때문에 자동 스크롤하고 싶지 않습니다.

사용자가 페이지의 맨 아래로 스크롤되는지 또는 페이지에서 더 높게 스크롤되었는지 어떻게 알 수 있습니까?


1
이것은 Angular 6에서 작동합니다-> stackoverflow.com/a/42547136/621951
Günay Gültekin

답변:


268
window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
        // you're at the bottom of the page
    }
};

데모보기


29
html / body 요소가 100 %로 설정되면 작동하지 않습니다 (바디가 전체 뷰포트 높이를 채우도록)
Grodriguez

5
IE document.documentElement.scrollTop대신 사용하십시오 window.scrollY. IE의 어떤 버전이 지원되는지 확실하지 않습니다 window.scrollY.
Batandwa

3
Chromium 버전 47.0.2526.73에서는 작동하지 않습니다. 기본 OS 0.3.2 (64 비트)에서 실행되는 Ubuntu 14.04 기반
K-SO의 독성이 증가하고 있습니다.

9
offsetHeight 대신 document.body.scrollHeight를 사용했습니다 (제 경우에는 offsetHeight가 항상 window.innerHeight보다 작습니다)
Oliver

1
@KarlMorrison 브라우저로 현상금 상을 수상한 답변 (@Dekel)을 사용해 볼 수 있습니까?
Basj

115

모든 주요 브라우저 지원을위한 업데이트 된 코드 (IE10 및 IE11 포함)

window.onscroll = function(ev) {
    if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
        alert("you're at the bottom of the page");
    }
};

현재 허용되는 답변의 문제점 window.scrollY은 IE에서 사용할 수 없다는 것입니다.

scrollY에 관한 mdn 의 인용문은 다음 과 같습니다.

브라우저 간 호환성을 위해 window.scrollY 대신 window.pageYOffset을 사용하십시오.

작업 스 니펫 :

Mac 참고 사항

@ Raphaël의 의견에 따르면, 작은 오프셋으로 인해 Mac에서 문제가 발생했습니다.
다음과 같은 업데이트 된 조건이 작동합니다.

(window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2

누군가 가이 특정 문제에 대해 언급 할 수 있다면 더 이상 테스트 할 기회가 없었습니다.


FF, Chrome, IE10, Chrome for Android 작업을 확인했습니다. @Dekel 감사합니다!
Basj

2
이상하게 들릴 수 있지만 브라우저에서만 1px가 부족하여 조건이 트리거되지 않습니다. 왜 그런지 잘 모르겠지만 몇 픽셀을 더 추가해야 작동합니다.
Sharjeel Ahmed

3
맥 컴퓨터, 아래의 조건 우리는과 같이 상태를 업데이트하기 때문에 작은 오프셋 (~ 1 x 1 픽셀)의 충족되지(window.innerHeight + window.pageYOffset) >= document.body.offsetHeight - 2
라파엘

4
thx @Dekel! 실제로, 우리는 window.pageYOffset이 mac에서 부동임을 알 수 있습니다. 우리의 최종 솔루션은 (window.innerHeight + Math.ceil(window.pageYOffset + 1)) >= document.body.offsetHeight입니다.
Raphaël

2
몸이 스타일이 경우에 작동하지 않습니다 세트 높이 100 %
raRaRa

56

받아 들인 대답이 효과가 없었습니다. 이것은했다 :

window.onscroll = function(ev) {
    if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) {
      // you're at the bottom of the page
      console.log("Bottom of page");
    }
};

구형 브라우저 (IE9)를 지원하려면 window.pageYOffset약간 더 나은 지원을 제공 하는 별칭 을 사용하십시오 .


1
IE10 / 11에서는 작동하지 않습니다. IE 지원에 대한 Dekel의 답변 ( stackoverflow.com/questions/9439725/… )을 확인하십시오 . 나를 위해 일했다
Herr_Schwabullek

다른 답변은 페이지 맨 아래에있을 때뿐만 아니라 스크롤 할 때마다 console.log ()를 트리거했습니다. 이 답변은 Chrome에서 효과적이었습니다.
Defcronyke

즉, edge에서 작동하지 않는 window.scrollY를 제거하면 괜찮은 대답입니다. 교체 : (window.innerHeight + window.pageYOffset)> = document.body.scrollHeight
colemerrick

21

답변을 찾고 있었지만 정확한 답변을 찾지 못했습니다. 다음은이 답변 당시 최신 Firefox, IE 및 Chrome에서 작동하는 순수한 자바 스크립트 솔루션입니다.

// document.body.scrollTop alone should do the job but that actually works only in case of Chrome.
// With IE and Firefox it also works sometimes (seemingly with very simple pages where you have
// only a <pre> or something like that) but I don't know when. This hack seems to work always.
var scrollTop = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;

// Grodriguez's fix for scrollHeight:
// accounting for cases where html/body are set to height:100%
var scrollHeight = (document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight;

// >= is needed because if the horizontal scrollbar is visible then window.innerHeight includes
// it and in that case the left side of the equation is somewhat greater.
var scrolledToBottom = (scrollTop + window.innerHeight) >= scrollHeight;

// As a bonus: how to scroll to the bottom programmatically by keeping the horizontal scrollpos:
// Since window.innerHeight includes the height of the horizontal scrollbar when it is visible
// the correct vertical scrollTop would be
// scrollHeight-window.innerHeight+sizeof(horizontal_scrollbar)
// Since we don't know the visibility/size of the horizontal scrollbar
// we scroll to scrollHeight that exceeds the value of the
// desired scrollTop but it seems to scroll to the bottom with all browsers
// without problems even when the horizontal scrollbar is visible.
var scrollLeft = (document.documentElement && document.documentElement.scrollLeft) || document.body.scrollLeft;
window.scrollTo(scrollLeft, scrollHeight);

4
이것은 거의 나를 위해 일한,하지만 난 사용했다 ((document.documentElement && document.documentElement.scrollHeight) || document.body.scrollHeight)대신의 document.body.scrollHeightHTML / 몸 높이로 설정되는 경우에 대한 계정 : 100 %
Grodriguez

1
@Grodriguez 정보 주셔서 감사합니다! 앞으로 우리에게 도움이 될 것입니다! :-)
pasztorpisti

15

이 작동합니다

window.onscroll = function() {

    // @var int totalPageHeight
    var totalPageHeight = document.body.scrollHeight; 

    // @var int scrollPoint
    var scrollPoint = window.scrollY + window.innerHeight;

    // check if we hit the bottom of the page
    if(scrollPoint >= totalPageHeight)
    {
        console.log("at the bottom");
    }
}

구형 브라우저 (IE9)를 지원하려면 window.scrollYwindow.pageYOffset으로 바꾸십시오.


1
이 작업은 2019 년에 반응합니다. 본문 100 % 높이, html 100 % 높이로 작업합니다. 크롬, 사파리, 파이어 폭스, 가장자리와 함께 작동합니다.
화난 키위

참고 사항 : 명명을 변경해야합니다-변수를 전환해야합니다. scrollHeight는 총 페이지 높이를 표시하고 totalHeight는 현재 스크롤 포인트를 표시하므로 약간 혼동됩니다.
블라디미르 마튼

4

방금 이것을보고 시작했으며 여기에 대한 답변이 도움이되었습니다. 감사합니다. IE7까지 코드가 안전하도록 조금 확장했습니다.

이것이 누군가에게 도움이되기를 바랍니다.

여기에 바이올린이 있습니다.)

    <!DOCTYPE html>
<html>
<head>
    <style>
        div {
            height: 100px;
            border-bottom: 1px solid #ddd;
        }

        div:nth-child(even) {
            background: #CCC
        }

        div:nth-child(odd) {
            background: #FFF
        }

    </style>
</head>

<body>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div>
<div></div><div></div><div></div><div></div><div></div><div></div><div></div>
</body>

<script type="text/javascript">
console.log("Doc Height = " + document.body.offsetHeight);
console.log("win Height = " + document.documentElement.clientHeight);
window.onscroll = function (ev) {
    var docHeight = document.body.offsetHeight;
    docHeight = docHeight == undefined ? window.document.documentElement.scrollHeight : docHeight;

    var winheight = window.innerHeight;
    winheight = winheight == undefined ? document.documentElement.clientHeight : winheight;

    var scrollpoint = window.scrollY;
    scrollpoint = scrollpoint == undefined ? window.document.documentElement.scrollTop : scrollpoint;

    if ((scrollpoint + winheight) >= docHeight) {
        alert("you're at the bottom");
    }
};
</script>
</html>

작품의 종류. 그러나 매우 정확하지 않습니다. 그것은 당신이 바닥의 약 16px 안에있는 한 아래쪽으로 스크롤되는 것으로 간주합니다.
피터 홀

4

height: 100%일부 컨테이너 <div id="wrapper">에서 설정 하는 경우 다음 코드가 작동합니다 (Chrome에서 테스트).

var wrapper = document.getElementById('wrapper');

wrapper.onscroll = function (evt) {
  if (wrapper.scrollTop + window.innerHeight >= wrapper.scrollHeight) {
    console.log('reached bottom!');
  }
}

3
window.onscroll = function(ev) {
    if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
        alert("you're at the bottom of the page");
    }
};

이 답변은 엣지 케이스를 수정합니다. pageYOffset 입니다 double동안 innerHeight하고 offsetHeight있는 long브라우저가 당신에게 정보를 제공 할 때 그래서, 당신은 픽셀 짧은 될 수있다. 예를 들어 페이지 하단에

진실 window.innerHeight = 10.2

진실 window.pageYOffset = 5.4

진실 document.body.offsetHeight = 15.6

우리의 계산은 다음과 같습니다 : 10 + 5.4> = 16 이것은 거짓입니다

이 문제를 해결하기 위해 우리는 할 수 있습니다 Math.ceilpageYOffset가치 에 대해 .

희망이 도움이됩니다.


3

jquery를 좋아한다면

$(window).scroll(function() {
  if($(window).scrollTop() + $(window).height() >= $(document).height()) {
    // doSomethingHere();
  }
});

누가 ... jQuery를 사랑하지 않는
조쉬 Habdas

2
@JoshHabdas 브라우저
Toni Michel Caubet

2

jquery의 무한 스크롤을 살펴볼 수 있습니다.

http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/

jquery 라이브러리를 사용하고 엄격한 순수 JS 메소드를 원치 않는다고 가정 할 때 원하는 것을하는 것처럼 들립니다.


2
이 링크가 질문에 대답 할 수 있지만 여기에 답변의 필수 부분을 포함시키고 참조 할 수있는 링크를 제공하는 것이 좋습니다. 링크 된 페이지가 변경되면 링크 전용 답변이 유효하지 않을 수 있습니다.
bobthedeveloper

@Hatsjoem 그는 플러그인에 연결하고 있습니다. 복사해야 할 "필수 부분"은 정확히 무엇입니까? 답변이 "링크 된 페이지가 변경되면 무효가됩니까?" 링크가 끊어지면 플러그인이 중단되어 더 이상 존재하지 않는다는 의미입니다. 답변에 더 많은 정보를 추가하더라도 여전히 유효하지 않습니다. Jeez, 링크 전용 답변이 반드시 나쁘지는 않습니다.
dcastro

@Hatsjoem 또한 메타에서 : "참조 된 라이브러리가 잘 알려진 안정된 위치에있을 때 이런 종류의 대답은 일반적으로 좋지 않은 대답 이지만 그럼에도 불구하고 대답 은"이것을 사용합니다 "라고 말합니다.
dcastro

또한 무한 스크롤 이이 URL을 변경하면 Google이 여전히 존재합니다. 요점은 해당 플러그인을 사용하는 것이므로 링크가 죽으면 Google 검색 jquery 무한 스크롤 만하면됩니다. 필요한 것을 찾을 수 있습니다.
Kai Qing

2

놀랍게도 어떤 해결책도 나를 위해 일하지 않았습니다. 내 생각 css이 엉망이고 body사용 할 때 모든 내용을 감싸지 않았기 때문이라고 생각합니다 height: 100%(아직 이유를 모릅니다). 그러나 해결책을 찾는 동안 나는 기본적으로 똑같은 것을 생각해 냈지만 아마도 볼만한 가치가 있습니다. 프로그래밍에 익숙하지 않습니다. 그...

window.onscroll = function(evt) {
  var check = (Element.getBoundingClientRect().bottom - window.innerHeight <= 0) ? true : false;
  if (check) { console.log("You're at the bottom!"); }
};

2
$(document).ready(function(){
    $('.NameOfYourDiv').on('scroll',chk_scroll);
});

function chk_scroll(e)
{
    var elem = $(e.currentTarget);
    if (elem[0].scrollHeight - elem.scrollTop() == elem.outerHeight()) 
    {
        alert("scrolled to the bottom");
    }

}

다른 관점을 확인하십시오. 그러나 허용 된 답변은 확실합니다
Zihan Zhang

2
const handleScroll = () => {
    if (Math.round(window.scrollY + window.innerHeight) >= Math.round(document.body.scrollHeight)) {
        onScroll();
    }
};

이 코드는 Firefox 및 IE에서도 효과적이었습니다.


1

기능 코드 스 니펫 내장 defaultView및 사용 documentElement:

const { defaultView } = document;
const { documentElement } = document;
const handler = evt => requestAnimationFrame(() => {
  const hitBottom = (() => (defaultView.innerHeight + defaultView.pageYOffset) >= documentElement.offsetHeight)();
  hitBottom
    ? console.log('yep')
    : console.log('nope')
});
document.addEventListener('scroll', handler);
<pre style="height:110vh;background-color:fuchsia">scroll down</pre>


1

창의 높이와 스크롤 상단의 결합 결과가 바디의 결과보다 큰지 확인할 수 있습니다

if (window.innerHeight + window.scrollY >= document.body.scrollHeight) {}


0

올바른 XPath를 모르는 구성 요소를 찾기 위해 체계적으로 아래로 스크롤하는 방법 (Java)을 생각해 내야했습니다 (긴 이야기이므로 그냥 따라 가십시오). 방금 언급했듯이 구성 요소를 찾는 동안 아래로 스크롤하여 구성 요소를 찾거나 페이지 아래쪽에 도달하면 중지해야했습니다.

다음 코드 스 니펫은 페이지 맨 아래로 스크롤을 제어합니다.

JavascriptExecutor js = (JavascriptExecutor) driver;
boolean found = false;
long currOffset = 0;
long oldOffset = 0;
do
{
    oldOffset = currOffset;
    // LOOP to seek the component using several xpath regexes removed
    js.executeScript("window.scrollBy(0, 100)");
    currOffset = (Long)js.executeScript("var offset = window.window.pageYOffset; return offset;");
} while (!found && (currOffset != oldOffset));

그건 그렇고,이 코드 스 니펫이 실행되기 전에 창이 최대화됩니다.


0

받아 들인 대답이 효과가 없었습니다. 이것은했다 :

const element = document.createElement('div');
document.body.appendChild(element);
document.addEventListener('scroll', () => {
    const viewportHeight = window.innerHeight;
    const distance = element.getBoundingClientRect().top;
    if (Math.floor(distance) <= viewportHeight) {
        console.log('yep')
    } else {
        console.log('nope')
    }
})

0

내가 찾은 두 가지 솔루션은 다음과 같습니다.

  window.addEventListener('scroll', function(e) {
    if (
      window.innerHeight + document.documentElement.scrollTop ===
      document.documentElement.offsetHeight
    ) {
      console.log('You are at the bottom')
    }
  })

그리고 나머지:

  window.addEventListener('scroll', function(e) {
    if (
      window.innerHeight + window.pageYOffset ===
      document.documentElement.offsetHeight
    ) {
      console.log('You are at the bottom')
    }
  })
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.