Scrolling
On this page
JavaScript Scrolling (JavaScript滚动)
The next event we are going to look through is scroll: one of the most frequently used events in JavaScript, and not only. With the help of this event, you can react to a page or element scrolling. Here are a few pretty good things to do with it:
Show or hide extra controls or information depending on where the user is in the document. Load more data, scrolling down up to the end of the page. (根据用户在文档中的位置显示或隐藏额外的控件或信息。 加载更多数据,向下滚动到页面末尾。)
A small function showing the current scroll is below:
window.addEventListener('scroll', function () {
document.getElementById('showScroll').innerHTML = window.pageYOffset + 'px';
});
The action is as follows: The current scroll is equal to 0…..px.
The scroll event operates on the window, as well as on scrollable elements. Window-relative coordinates of the whole document can be received as document.documentElement.getBoundingClientRect(), the bottom property can be wondow-relative coordinate of the bottom of the document.The window height can be obtained as document.documentElement.clientHeight:
<!DOCTYPE html>
<html>
<head>
<title>Title of the Document</title>
</head>
<body>
<h1>Scroll page</h1>
<script>
function scrollBottom() {
while(true) {
let windowRelativeBottom = document.documentElement.getBoundingClientRect().bottom;
// if the user scrolled far enough (<500px to the end)
if(windowRelativeBottom > document.documentElement.clientHeight + 500) break;
document.body.insertAdjacentHTML("beforeend", `<p>Date: ${new Date()}</p>`);
}
}
window.addEventListener('scroll', scrollBottom);
scrollBottom(); // init document
</script>
</body>
</html>
Prevent Scrolling
Prevent Scrolling (防止滚动)
Let’s learn to make something unscrollable. (让我们学会做一些不可滚动的东西。)
It is not possible to prevent scrolling with event.preventDefault() in onscroll listener. The reason is that it triggers only after the scroll has taken place. But, there is another means that can prevent scrolling - it’s using event.preventDefault() on the event, which causes the scroll. For example, the keydown event.preventDefault() for pageUp and pageDown. Adding an event handler to the mentioned events with –onto will stop the scrolling. (无法阻止在滚动侦听器中使用event.preventDefault ()进行滚动。原因是它只有在滚动发生后才会触发。但是,还有另一种方法可以防止滚动-它对事件使用event.preventDefault () ,这会导致滚动。例如, pageUp和pageDown的keydown event.preventDefault ()。使用–onto将事件处理程序添加到上述事件将停止滚动。)
There is a variety of ways to start scrolling, but the most reliable one is to use the CSS overflow property. (开始滚动有多种方法,但最可靠的方法是使用CSS溢出属性。)