Ответ 1
window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
// you're at the bottom of the page
}
};
Мне нужно определить, прокручивается ли пользователь в нижней части страницы. Если они находятся в нижней части страницы, когда я добавляю новый контент в нижнюю часть, я автоматически прокручу их до нового нижнего. Если они не находятся внизу, они читают предыдущий контент выше на странице, поэтому я не хочу автоматически прокручивать их, так как они хотят оставаться там, где они есть.
Как определить, прокручивается ли пользователь в нижней части страницы или прокручивается выше на странице?
window.onscroll = function(ev) {
if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
// you're at the bottom of the page
}
};
window.onscroll = function(ev) {
if ((window.innerHeight + window.pageYOffset) >= document.body.offsetHeight) {
alert("you're at the bottom of the page");
}
};
Проблема с текущим принятым ответом заключается в том, что window.scrollY
недоступен в IE.
Вот цитата из mdn относительно scrollY:
Для кросс-браузерной совместимости используйте window.pageYOffset вместо window.scrollY.
И рабочий фрагмент:
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>
Принятый ответ не работал для меня. Это сделал:
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
который имеет немного лучшую поддержку.
Я искал ответ, но не нашел точного. Вот чистое решение для JavaScript, которое работает с последними версиями 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 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 scrollHeight, totalHeight;
scrollHeight = document.body.scrollHeight;
totalHeight = window.scrollY + window.innerHeight;
if(totalHeight >= scrollHeight)
{
console.log("at the bottom");
}
}
Я только начал смотреть на это, и ответы здесь помогли мне, поэтому спасибо за это. Я немного расширил, чтобы код был безопасным вплоть до 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>
Если вы устанавливаете 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!');
}
}
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
, поэтому, когда браузер предоставляет вам информацию, вы можете быть краткими.
Например: внизу страницы
true window.innerHeight = 10.2
true window.pageYOffset = 5.4
true document.body.offsetHeight = 15.6
Наш расчет тогда будет: 10 + 5.4 >= 16, который false
Чтобы исправить это, мы можем сделать Math.ceil
по значению pageYOffset
.
Надеюсь, что это поможет.
Вы можете просмотреть бесконечную прокрутку jquery:
http://www.infinite-scroll.com/infinite-scroll-jquery-plugin/
Кажется, что он делает то, о чем вы просите, предполагая, что вы готовы использовать библиотеку jquery и не надеетесь на строгий чистый JS-метод.
Удивительно, но ни один из решений не работал у меня. Я думаю, потому что мой 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!"); }
};
$(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");
}
}
если ты любишь jquery
$(window).scroll(function() {
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
// doSomethingHere();
}
});
Использование 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>
Мне пришлось придумать способ (на Java), чтобы систематически прокручивать вниз в поисках компонента, для которого я не знал правильный XPath (длинная история, так что просто подыграйте). Как я только что сказал, мне нужно было прокрутить вниз при поиске компонента и остановиться либо тогда, когда компонент был найден, либо достигнут конец страницы.
Следующий фрагмент кода управляет прокруткой вниз до нижней части страницы:
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));
Кстати, окно развернуто до того, как этот фрагмент кода будет выполнен.
Принятый ответ не работал для меня. Это сделал:
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')
}
})
const handleScroll = () => {
if (Math.round(window.scrollY + window.innerHeight) >= Math.round(document.body.scrollHeight)) {
onScroll();
}
};
Этот код работал и для меня в Firefox и IE.