사용자가 맨 아래로 스크롤했는지 확인합니다(창뿐만 아니라 모든 요소).
사용자가 아래로 스크롤하면 콘텐츠가 로딩되는 페이지화 시스템(Facebook 등)을 만들고 있습니다.가장 좋은 방법은 사용자가 페이지 하부에 있을 때를 찾아 Ajax 쿼리를 실행하여 더 많은 게시물을 로드하는 것입니다.
유일한 문제는 사용자가 페이지 하단으로 스크롤했는지 확인하는 방법을 모른다는 것입니다.좋은 생각 있어요?
저는 jQuery를 사용하고 있기 때문에, 그것을 사용하는 답변을 자유롭게 주세요.
이벤트 사용:window 이렇게요.
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == $(document).height()) {
alert("bottom!");
}
});
여기서 테스트할 수 있습니다.이렇게 하면 창의 맨 위 스크롤이 됩니다.따라서 스크롤된 스크롤의 양은 표시되는 창의 높이를 더하여 전체 콘텐츠의 높이와 동일한지 여부를 확인합니다.document사용자가 맨 아래쪽에 있는지 확인하는 경우 다음과 같이 표시됩니다.
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
alert("near bottom!");
}
});
여기서 해당 버전을 테스트할 수 있습니다. 조정만 하면 됩니다.100이치노
왜 이것이 아직 게시되지 않았는지 정확히 알 수 없지만 MDN의 설명서에 따르면 가장 간단한 방법은 네이티브 javascript 속성을 사용하는 것입니다.
element.scrollHeight - element.scrollTop === element.clientHeight
스크롤 가능한 요소의 맨 아래에 있으면 true를 반환합니다.javascript를 사용하면 다음과 같습니다.
element.addEventListener('scroll', function(event)
{
var element = event.target;
if (element.scrollHeight - element.scrollTop === element.clientHeight)
{
console.log('scrolled');
}
});
scrollHeight하게 말하면, 「8」입니다.clientHeight ★★★★★★★★★★★★★★★★★」scrollTop이랬다 ie 6 6도 마찬가지입니다.이치노
없이 잘 합니다. Nick Craver의 가 있다는 .$(document).height()브라우저에 따라 다릅니다.
모든 브라우저에서 작동하려면 James Padolsey의 다음 기능을 사용합니다.
function getDocHeight() {
var D = document;
return Math.max(
D.body.scrollHeight, D.documentElement.scrollHeight,
D.body.offsetHeight, D.documentElement.offsetHeight,
D.body.clientHeight, D.documentElement.clientHeight
);
}
$(document).height()최종 코드는 다음과 같습니다.
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() == getDocHeight()) {
alert("bottom!");
}
});
또한 Nick Craver의 탁월한 답변에 따라 스크롤이벤트가 자주 실행되지 않도록 조정하여 브라우저 성능을 향상시킬 수 있습니다.
var _throttleTimer = null;
var _throttleDelay = 100;
var $window = $(window);
var $document = $(document);
$document.ready(function () {
$window
.off('scroll', ScrollHandler)
.on('scroll', ScrollHandler);
});
function ScrollHandler(e) {
//throttle event:
clearTimeout(_throttleTimer);
_throttleTimer = setTimeout(function () {
console.log('scroll');
//do work
if ($window.scrollTop() + $window.height() > $document.height() - 100) {
alert("near bottom!");
}
}, _throttleDelay);
}
Nick Craver의 답변은 iOS 6 Safari Mobile에서 작동하도록 약간 수정해야 하며 다음과 같습니다.
$(window).scroll(function() {
if($(window).scrollTop() + window.innerHeight == $(document).height()) {
alert("bottom!");
}
});
$(창) 변경.high() to window.innerHeight를 실행해야 합니다.이것은 주소 표시줄이 숨겨지면 창 높이에 60px가 추가되기 때문입니다.$(window).height()를 사용하는 동안 이 변경은 반영되지 않습니다.window.innerHeight
주의:window.innerHeight에는 가로 경우)도됩니다.$(window).height()수평 스크롤바의 높이는 포함되지 않습니다.이것은 Mobile Safari에서는 문제가 되지 않지만 다른 브라우저나 향후 버전의 Mobile Safari에서는 예기치 않은 동작이 발생할 수 있습니다.「」의 변경==로로 합니다.>=대부분의 일반적인 사용 사례에서 이 문제를 해결할 수 있습니다.
은 이쪽window.innerHeight여기의 재산
여기 꽤 간단한 접근법이 있습니다.
const didScrollToBottom = elm.scrollTop + elm.clientHeight == elm.scrollHeight
예
elm.onscroll = function() {
if(elm.scrollTop + elm.clientHeight == elm.scrollHeight) {
// User has scrolled to the bottom of the element
}
}
서 ★★★★★elm 、 에 、 i 、 i i i i i i i i i from from from에서 취득한 입니다.document.getElementById.
이 답변을 확인해 주세요.
window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
console.log("bottom");
}
};
수 있다footerHeight - document.body.offsetHeight합니다.
다음은 코드 디버깅에 도움이 되는 코드입니다.위 답변을 테스트해 보니 버그가 있습니다.Chrome, IE, Firefox, IPad(Safari)에서 다음 테스트를 합니다.테스트할 다른 장치가 설치되어 있지 않습니다.
<script type="text/javascript">
$(function() {
$(window).scroll(function () {
var docElement = $(document)[0].documentElement;
var winElement = $(window)[0];
if ((docElement.scrollHeight - winElement.innerHeight) == winElement.pageYOffset) {
alert('bottom');
}
});
});
</script>
보다 심플한 솔루션이 있을지도 모르지만, IT부문이 기능하는 시점에서 중단했습니다.
일부 악성 브라우저에 아직 문제가 있는 경우 디버깅에 도움이 되는 코드를 다음에 나타냅니다.
<script type="text/javascript">
$(function() {
$(window).scroll(function () {
var docElement = $(document)[0].documentElement;
var details = "";
details += '<b>Document</b><br />';
details += 'clientHeight:' + docElement.clientHeight + '<br />';
details += 'clientTop:' + docElement.clientTop + '<br />';
details += 'offsetHeight:' + docElement.offsetHeight + '<br />';
details += 'offsetParent:' + (docElement.offsetParent == null) + '<br />';
details += 'scrollHeight:' + docElement.scrollHeight + '<br />';
details += 'scrollTop:' + docElement.scrollTop + '<br />';
var winElement = $(window)[0];
details += '<b>Window</b><br />';
details += 'innerHeight:' + winElement.innerHeight + '<br />';
details += 'outerHeight:' + winElement.outerHeight + '<br />';
details += 'pageYOffset:' + winElement.pageYOffset + '<br />';
details += 'screenTop:' + winElement.screenTop + '<br />';
details += 'screenY:' + winElement.screenY + '<br />';
details += 'scrollY:' + winElement.scrollY + '<br />';
details += '<b>End of page</b><br />';
details += 'Test:' + (docElement.scrollHeight - winElement.innerHeight) + '=' + winElement.pageYOffset + '<br />';
details += 'End of Page? ';
if ((docElement.scrollHeight - winElement.innerHeight) == winElement.pageYOffset) {
details += 'YES';
} else {
details += 'NO';
}
$('#test').html(details);
});
});
</script>
<div id="test" style="position: fixed; left:0; top: 0; z-index: 9999; background-color: #FFFFFF;">
나는 이것이 누군가의 시간을 절약해 주길 바란다.
var elemScrolPosition = elem.scrollHeight - elem.scrollTop - elem.clientHeight;
요소의 하단까지의 거리 스크롤 막대를 계산합니다.스크롤 막대가 맨 아래에 도달한 경우 0이 됩니다.
제 의견은 이렇습니다.
$('#container_element').scroll( function(){
console.log($(this).scrollTop()+' + '+ $(this).height()+' = '+ ($(this).scrollTop() + $(this).height()) +' _ '+ $(this)[0].scrollHeight );
if($(this).scrollTop() + $(this).height() == $(this)[0].scrollHeight){
console.log('bottom found');
}
});
와 ES6를 입니다.debounce:
document.addEventListener('scroll', debounce(() => {
if(document.documentElement.scrollHeight === window.pageYOffset + window.innerHeight) {
// Do something
}
}, 500))
function debounce(e,t=300){let u;return(...i)=>{clearTimeout(u),u=setTimeout(()=>{e.apply(this,i)},t)}}
데모: https://jsbin.com/jicikaruta/1/edit?js,output
참고 자료:
플레인 js의 솔루션:
let el=document.getElementById('el');
el.addEventListener('scroll', function(e) {
if (this.scrollHeight - this.scrollTop - this.clientHeight<=0) {
alert('Bottom');
}
});
#el{
width:400px;
height:100px;
overflow-y:scroll;
}
<div id="el">
<div>content</div>
<div>content</div>
<div>content</div>
<div>content</div>
<div>content</div>
<div>content</div>
<div>content</div>
<div>content</div>
<div>content</div>
<div>content</div>
<div>content</div>
</div>
스크롤 이벤트를 듣는 대신 Intersection Observer를 사용하면 뷰포트에 마지막 요소가 표시되는지 확인할 수 있습니다(즉, 사용자가 아래로 스크롤된 경우).또, 폴리필을 사용한 IE7도 서포트되고 있습니다.
var observer = new IntersectionObserver(function(entries){
if(entries[0].isIntersecting === true)
console.log("Scrolled to the bottom");
else
console.log("Not on the bottom");
}, {
root:document.querySelector('#scrollContainer'),
threshold:1 // Trigger only when whole element was visible
});
observer.observe(document.querySelector('#scrollContainer').lastElementChild);
#scrollContainer{
height: 100px;
overflow: hidden scroll;
}
<div id="scrollContainer">
<div>Item 1</div>
<div>Item 2</div>
<div>Item 3</div>
<div>Item 4</div>
<div>Item 5</div>
<div>Item 6</div>
<div>Item 7</div>
<div>Item 8</div>
<div>Item 9</div>
<div>Item 10</div>
</div>
Nick은 정상적으로 응답하지만 스크롤 중에 반복되거나 사용자가 창을 확대/축소하면 전혀 작동하지 않습니다.첫 번째 키를 돌았을 때 간단한 수정이 떠올랐고 예상대로 작동합니다.
if (Math.round($(window).scrollTop()) + $(window).innerHeight() == $(document).height()){
loadPagination();
$(".go-up").css("display","block").show("slow");
}
의 맨 해야 하는 <div>이 코드 라인을 사용하여 구현했습니다.
window.addEventListener("scroll", () => {
var offset = element.getBoundingClientRect().top - element.offsetParent.getBoundingClientRect().top;
const top = window.pageYOffset + window.innerHeight - offset;
if (top === element.scrollHeight) {
console.log("bottom");
}
}, { passive: false });
저는 순수 JS로 아주 쉬운 방법으로 해왔습니다.
function onScroll() {
if (window.pageYOffset + window.innerHeight >= document.documentElement.scrollHeight - 50) {
Console.log('Reached bottom')
}
}
window.addEventListener("scroll", onScroll);
Firefox와 Chrome에서는 이 모든 솔루션이 작동하지 않기 때문에 Miles Okeefe와 meder omuraliev의 커스텀 기능을 다음과 같이 사용하고 있습니다.
function getDocHeight()
{
var D = document;
return Math.max(
D.body.scrollHeight, D.documentElement.scrollHeight,
D.body.offsetHeight, D.documentElement.offsetHeight,
D.body.clientHeight, D.documentElement.clientHeight
);
}
function getWindowSize()
{
var myWidth = 0, myHeight = 0;
if( typeof( window.innerWidth ) == 'number' ) {
//Non-IE
myWidth = window.innerWidth;
myHeight = window.innerHeight;
} else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
//IE 6+ in 'standards compliant mode'
myWidth = document.documentElement.clientWidth;
myHeight = document.documentElement.clientHeight;
} else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
//IE 4 compatible
myWidth = document.body.clientWidth;
myHeight = document.body.clientHeight;
}
return [myWidth, myHeight];
}
$(window).scroll(function()
{
if($(window).scrollTop() + getWindowSize()[1] == getDocHeight())
{
alert("bottom!");
}
});
다음 코드를 사용해 보세요.
$("#dashboard-scroll").scroll(function(){
var ele = document.getElementById('dashboard-scroll');
if(ele.scrollHeight - ele.scrollTop === ele.clientHeight){
console.log('at the bottom of the scroll');
}
});
하단까지 스크롤하는 경우 일치 조건에 대해 이 작업을 시도하십시오.
if ($(this)[0].scrollHeight - $(this).scrollTop() ==
$(this).outerHeight()) {
//code for your custom logic
}
이렇게 하면 스크롤 가능한 요소를 확인할 때(즉, 그렇지 않음) 정확한 결과를 얻을 수 있습니다.window):
// `element` is a native JS HTMLElement
if ( element.scrollTop == (element.scrollHeight - element.offsetHeight) )
// Element scrolled to bottom
offsetHeight요소의 실제 가시 높이(패딩, 여백 및 스크롤바 포함)를 제공해야 한다.scrollHeight는, 보이지 않는(비활성화) 영역을 포함한 요소의 전체 높이입니다.
jQuery의.outerHeight()JS와 유사한 결과를 제공해야 합니다..offsetHeight-- MDN에 기재되어 있는 문서offsetHeight교차 지원 여부가 불분명합니다.더 많은 옵션을 포함하려면 다음 사항을 더 자세히 설명하십시오.
var offsetHeight = ( container.offsetHeight ? container.offsetHeight : $(container).outerHeight() );
if ( container.scrollTop == (container.scrollHeight - offsetHeight) ) {
// scrolled to bottom
}
아래쪽에 도달한 스크롤을 감지하기 위해 이 테스트를 사용했습니다. event.target.scrollTop === event.target.scrollHeight - event.target.offsetHeight
받아들여진 답변이 나에게 효과가 없었기 때문에 내 의견은 이렇다.
var documentAtBottom = (document.documentElement.scrollTop + window.innerHeight) >= document.documentElement.scrollHeight;
구글 크롬은 전화하면 페이지 전체 높이를 제공합니다.$(window).height()
대신,window.innerHeight창 높이를 가져옵니다.필요한 검사는 다음과 같습니다.
if($(window).scrollTop() + window.innerHeight > $(document).height() - 50) {
console.log("reached bottom!");
}
다른 많은 솔루션이 작동하지 않습니다.아래쪽으로 스크롤할 때 div가 경고를 2번 트리거하고 위로 이동할 때 최대 몇 픽셀까지 트리거했기 때문에 해결책은 다음과 같습니다.
$('#your-div').on('resize scroll', function()
{
if ($(this).scrollTop() +
$(this).innerHeight() >=
$(this)[0].scrollHeight + 10) {
alert('reached bottom!');
}
});
Safari는 어플리케이션의 버그를 일으키고 있는 페이지 하단을 스크롤 할 수 있습니다.다음을 사용하여 해결>=대신===.
container.scrollTop >= container.scrollHeight - container.clientHeight
가장 간단한 방법은 다음과 같습니다.
const handleScroll = () => {
if (window.innerHeight + window.pageYOffset >= document.body.offsetHeight) {
console.log('scrolled to the bottom')
}}
window.addEventListener('scroll', handleScroll)
(2021) 여기서의 많은 답변에는 다음 항목에 대한 참조가 포함됩니다.element단, 페이지 전체에만 관심이 있는 경우 다음을 사용하십시오.
function isBottom() {
const { scrollHeight, scrollTop, clientHeight } = document.documentElement;
const distanceFromBottom = scrollHeight - scrollTop - clientHeight;
return distanceFromBottom < 20; // adjust the number 20 yourself
}
JQuery 없이 어프로치를 보여드릴게요.단순 JS 함수:
function isVisible(elem) {
var coords = elem.getBoundingClientRect();
var topVisible = coords.top > 0 && coords.top < 0;
var bottomVisible = coords.bottom < shift && coords.bottom > 0;
return topVisible || bottomVisible;
}
사용 방법의 간단한 예:
var img = document.getElementById("pic1");
if (isVisible(img)) { img.style.opacity = "1.00"; }
@danone answear를 사용하고 Ajax call을 추가했습니다.
$('#mydiv').on('scroll', function(){
function infiniScroll(this);
});
function infiniScroll(mydiv){
console.log($(mydiv).scrollTop()+' + '+ $(mydiv).height()+' = '+ ($(mydiv).scrollTop() + $(mydiv).height()) +' _ '+ $(mydiv)[0].scrollHeight );
if($(mydiv).scrollTop() + $(mydiv).height() == $(mydiv)[0].scrollHeight){
console.log('bottom found');
if(!$.active){ //if there is no ajax call active ( last ajax call waiting for results ) do again my ajax call
myAjaxCall();
}
}
}
Nick의 답변에 대한 반복적인 경고를 중지하려면
ScrollActivate();
function ScrollActivate() {
$(window).on("scroll", function () {
if ($(window).scrollTop() + $(window).height() > $(document).height() - 100) {
$(window).off("scroll");
alert("near bottom!");
}
});
}
언급URL : https://stackoverflow.com/questions/3898130/check-if-a-user-has-scrolled-to-the-bottom-not-just-the-window-but-any-element
'programing' 카테고리의 다른 글
| Larabel 5.2 - pluc() 메서드가 어레이를 반환합니다. (0) | 2022.11.10 |
|---|---|
| Larabel: MariaDB - 장인 이행: 갱신 행 (0) | 2022.11.10 |
| Python이 목록 사전을 만듭니다. (0) | 2022.11.10 |
| 권장되지 않는 Java Http Client - 얼마나 어렵습니까? (0) | 2022.11.10 |
| vuej의 tslint 오류를 자동 수정하려면 어떻게 해야 합니까? (0) | 2022.11.10 |