programing

브라우저 창이 아래로 스크롤되는지 여부를 감지하는 방법

bestcode 2022. 9. 22. 00:29
반응형

브라우저 창이 아래로 스크롤되는지 여부를 감지하는 방법

사용자가 페이지 맨 아래로 스크롤되는지 여부를 감지해야 합니다.페이지 맨 아래에 있는 경우 아래에 새 콘텐츠를 추가할 때 자동으로 새 콘텐츠 맨 아래로 스크롤합니다.아래가 아니면 페이지 상단에서 이전 내용을 읽고 있기 때문에 그대로 있고 싶기 때문에 자동 스크롤을 하고 싶지 않습니다.

사용자가 페이지 하단으로 스크롤되었는지 또는 사용자가 페이지 상단으로 스크롤되었는지 여부를 감지하려면 어떻게 해야 합니까?

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

데모 참조

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

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

는 이 답변이 문제라는 입니다.window.scrollYIE에서는 할 수 .

다음은 mdn에서 scrollY에 대한 견적입니다.

브라우저 간 호환성을 위해 window.page를 사용합니다.window.scrollY가 아닌 YOffset.

작업 중인 토막:

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

mac에 대한 주의사항

@Raphael의 코멘트를 바탕으로 작은 오프셋으로 인해 Mac에 문제가 발생하였습니다.
다음과 같은 업데이트된 조건이 작동합니다.

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

더 이상 테스트할 기회가 없었는데, 이 문제에 대해 누군가 의견을 주시면 감사하겠습니다.

받아들여진 답변은 나에게 효과가 없었다.이것은 다음과 같습니다.

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조금 더 나은 지지대를 가지고 있습니다.

나는 답을 찾고 있었지만 정확한 답을 찾지 못했다.다음은 최신 Firefox, IE 및 Chrome에서 작동하는 순수 Javascript 솔루션입니다.

// 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);

이것은 동작합니다.

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.scrollY를 window.page바꿉니다.세트

를 설정하는 경우height: 100% <div id="wrapper">크롬의

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

wrapper.onscroll = function (evt) {
  if (wrapper.scrollTop + window.innerHeight >= wrapper.scrollHeight) {
    console.log('reached bottom!');
  }
}
window.onscroll = function(ev) {
    if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
        alert("you're at the bottom of the page");
    }
};

대소문자를 합니다. 이 은 가장자리 대소문자를 수정하기 때문입니다.이거는pageYOffsetdouble 동시에innerHeight ★★★★★★★★★★★★★★★★★」offsetHeightlong브라우저에 정보가 뜨면 픽셀이 부족할 수 있습니다.를 들어, 있는 맨 과 같은 것들이 있습니다.

진실의 window.innerHeight = 10.2

진실의 window.pageYOffset = 5.4

진실의 document.body.offsetHeight = 15.6

그러면 우리의 계산은 10 + 5.4 > = 16이 됩니다. 이는 거짓입니다.

를 해결하려면 을(를) 합니다.Math.ceil pageYOffsetdiscloss.discloss 。

도움이 됐으면 좋겠다.

이제 막 이걸 보기 시작했는데, 여기 답이 도움이 됐어요. 감사합니다.코드가 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>

만약 다른 사람들과 운이 안 좋았다면 이 방법을 시도해 보세요.

window.onscroll = function() {
    const difference = document.documentElement.scrollHeight - window.innerHeight;
    const scrollposition = document.documentElement.scrollTop; 
    if (difference - scrollposition <= 2) {
        alert("Bottom of Page!"); 
    }   
}

$(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");
    }

}

당신이 jqueryoufter you like jquery

$(window).scroll(function() {
  if($(window).scrollTop() + $(window).height() >= $(document).height()) {
    // doSomethingHere();
  }
});
const handleScroll = () => {
    if (Math.round(window.scrollY + window.innerHeight) >= Math.round(document.body.scrollHeight)) {
        onScroll();
    }
};

이 코드는 Firefox와 IE에서도 사용할 수 있었습니다.

새로운 솔루션

한 가지 문제는 표준 메인 스크롤 요소가 부족하기 때문입니다.최근에 구현한 document.scrollingElement를 사용하여 이 문제를 해결할 수 있습니다.다음은 폴백 기능이 있는 크로스 브라우저 솔루션입니다.

function atEnd() {
    var c = [document.scrollingElement.scrollHeight, document.body.scrollHeight, document.body.offsetHeight].sort(function(a,b){return b-a}) // select longest candidate for scrollable length
    return (window.innerHeight + window.scrollY + 2 >= c[0]) // compare with scroll position + some give
}
function scrolling() {
    if (atEnd()) 
        //do something
}
window.addEventListener('scroll', scrolling, {passive: true});

놀랍게도 어떤 해결책도 제게는 효과가 없었습니다.내 생각엔 내 생각엔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!"); }
};

기능 코드 스니펫이 내장된 및 사용:

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>

위에서 설명한 바와 같이 일부 디바이스 및 브라우저에서는 코드가 작동하지 않을 수 있습니다.아래는 모든 브라우저(Chrome, IE, Edge, Firefox 및 Safari)에서 모든 주요 장치(iPhone, Android, PC)와 호환되는 테스트된 작업 코드입니다.

window.onscroll = function(ev) {
    var pageHeight = Math.max(document.body.scrollHeight, document.body.offsetHeight,  document.documentElement.clientHeight,  document.documentElement.scrollHeight,  document.documentElement.offsetHeight );
    if ((window.innerHeight + window.scrollY) >= pageHeight) {
        console.log("You are at the bottom of the page.");
    }
};
<html>
<body>
  <div style="width:100%; height:1500px">
    <p>Keep scrolling the page till end...</p>
  </div>
</body>
</html>

vanilla javascript를 사용하는 가장 간단한 방법

container.addEventListener('scroll', (e) => {
  var element = e.target;
  if (element.scrollHeight - element.scrollTop - element.clientHeight <= 0) {
    console.log('scrolled to bottom');
  }
});

창의 높이와 스크롤 상단의 합계가 본체보다 큰지 확인할 수 있습니다.

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

나에게 효과가 있는 솔루션을 2개 찾았습니다.

  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')
    }
  })

모바일 디바이스와 데스크톱용으로 이 기능을 사용해보겠습니다.여기서는 모바일/안드로이드 디바이스에서 동작하지 않는 코멘트가 있습니다.이 질문에 대해 감사합니다.코더로 유지!

    window.addEventListener("scroll", function(el) {
    const scrollY = window.scrollY + window.innerHeight + 2;
    const bodyScroll = document.body.offsetHeight;

    console.log("Scroll Y : " + scrollY);
    console.log("Body : " + bodyScroll);

    if(scrollY >= bodyScroll){
      alert("Bottom Page");
    }
  })

정확한 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));

덧붙여서 이 코드 스니펫이 실행되기 전에 창을 최대화한다.

loading="loading"으로 페이지 하단에 작은 이미지를 배치하기만 하면 되기 때문에 사용자가 아래로 스크롤 했을 때만 브라우저가 로딩됩니다.그러면 이미지가 실제 이미지를 반환하는 php 카운터 스크립트를 트리거합니다.

 <img loading="lazy" src="zaehler_seitenende.php?rand=<?=rand(1,1000);?>">

 <?php
 @header("Location: https://domain.de/4trpx.gif");

언급URL : https://stackoverflow.com/questions/9439725/how-to-detect-if-browser-window-is-scrolled-to-bottom

반응형