在 JavaScript 中自动滚动到页面底部

Mehvish Ashiq 2023年12月11日
  1. 使用 JavaScript scrollTo 函数滚动到底部
  2. 使用 JavaScript scrollIntoView 函数滚动到底部
  3. 使用 JavaScript scrollTop 函数滚动到底部
  4. 使用 JavaScript ScrollingElement 函数滚动到底部
  5. 使用 JavaScript scrollBy 函数滚动到底部
在 JavaScript 中自动滚动到页面底部

我们旨在向你介绍使用 JavaScript 自动滚动到页面底部的不同方法。本教程还教你滚动到带有和不带有动画的屏幕上的特定坐标。

使用 JavaScript scrollTo 函数滚动到底部

HTML 代码:

<!DOCTYPE html>
<html>
  <head>
    <title>Scroll Automatically</title>
  </head>
  <body id='main_body'>
      <button id="bottompage">Bottom</button>
      <div id="headingone">
           <h1>Heading One</h1>
           <img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		 background-of-software-developer-picture-id1294521676?                      
           b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			   alt="Programming Picture">
           <p>
           Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum 			 has been the industry's standard dummy text ever since the 1500s, when an unknown 			   printer took a galley of type and scrambled it to make a type specimen book. It has 			   survived not only five centuries, but also the leap into electronic typesetting, 			   remaining essentially unchanged. It was popularised in the 1960s with the release of 		   Letraset sheets containing Lorem Ipsum passages, and more recently with desktop 				   publishing software like Aldus PageMaker including versions of Lorem Ipsum.
           </p>
      </div>
 	  <div id="headingtwo">
 		<h1>Heading Two</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      
        b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      
        b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
        <p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum 			has been the industry's standard dummy text ever since the 1500s, when an unknown 			    printer took a galley of type and scrambled it to make a type specimen book. It has 			survived not only five centuries, but also the leap into electronic typesetting, 			    remaining essentially unchanged. It was popularised in the 1960s with the release of 		    Letraset sheets containing Lorem Ipsum passages, and more recently with desktop 				publishing software like Aldus PageMaker including versions of Lorem Ipsum.
        </p>
     </div>
     <div id="headingthree">
       <h1>Heading Three</h1>
       <img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		 background-of-software-developer-picture-id1294521676?                      
       b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			   alt="Programming Picture">
 	   <p>
       Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem         	   Ipsum has been the industry's standard dummy text ever since the 1500s, when an         		   unknown printer took a galley of type and scrambled it to make a type specimen         		   book. It has survived not only five centuries, but also the leap into electronic         	   typesetting, remaining essentially unchanged. It was popularised in the 1960s          		   with the release of Letraset sheets containing Lorem Ipsum passages, and more           		   recently with desktop publishing software like Aldus PageMaker including versions           		of Lorem Ipsum.
 	   </p>
 	</div>
 	<h1> Hi There! </h1>
 </body>
</html>

CSS 代码:

button{
 float:right;
 background-color:yellow;
 color:red;
}

JavaScript 代码:

document.querySelector('#bottompage').addEventListener('click', () => {
  window.scrollTo(0, document.body.scrollHeight);
})

上面给出的代码选择了 id 值为 bottompage 的标签元素。每当单击它时,就会触发一个滚动到页面底部(垂直滚动)的事件,因为 x 设置为 0y 设置为 document.body.scrollHeight,即 1655px

scrollTo 函数用于将 document 滚动到提供的网页坐标。如果滚动条可见并且文档与屏幕相比较大,则此方法有效。

scrollTo() 方法的两个参数都是必需的。参数 x 以像素为单位表示水平滚动多少,而以像素为单位表示垂直滚动的量为 y

你可能正在考虑如何计算高度?为此,你可以阅读 this 以了解所有高度计算。

使用 JavaScript scrollIntoView 函数滚动到底部

HTML 代码:

<!DOCTYPE html>
<html>
 <head>
 	<title>Scroll Automatically</title>
 </head>
 <body id='main_body'>
 	<p>
    Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum      	has been the industry's standard dummy text ever since the 1500s, when an unknown printer         took a galley of type and scrambled it to make a type specimen book. It has survived not         only five centuries, but also the leap into electronic typesetting, remaining essentially         unchanged. It was popularised in the 1960s with the release of Letraset sheets containing         Lorem Ipsum passages, and more recently with desktop publishing software like Aldus               PageMaker including versions of Lorem Ipsum.
    </p>
 
 	<a id="heading_one" href="javascript:void(0)">Heading 1</a>
 	<a id="heading_two" href="javascript:void(0)">Heading 2</a>
 	<a id="heading_three" href="javascript:void(0)">Heading 3</a>
 
	<div id="headingone">
 		<h1>Heading One</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-        	 background-of-software-developer-picture-id1294521676?                      
        b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem        		Ipsum has been the industry's standard dummy text ever since the 1500s, when an         		unknown printer took a galley of type and scrambled it to make a type specimen            		  book. It has survived not only five centuries, but also the leap into electronic        		  typesetting, remaining essentially unchanged. It was popularised in the 1960s           		  with the release of Letraset sheets containing Lorem Ipsum passages, and more           		  recently with desktop publishing software like Aldus PageMaker including versions         		of Lorem Ipsum.
 		</p>
 	</div>
 	<div id="headingtwo">
 		<h1>Heading Two</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-        	 background-of-software-developer-picture-id1294521676?                      
        b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem        		Ipsum has been the industry's standard dummy text ever since the 1500s, when an         		unknown printer took a galley of type and scrambled it to make a type specimen            		  book. It has survived not only five centuries, but also the leap into electronic        		  typesetting, remaining essentially unchanged. It was popularised in the 1960s           		  with the release of Letraset sheets containing Lorem Ipsum passages, and more           		  recently with desktop publishing software like Aldus PageMaker including versions         		of Lorem Ipsum.
 		</p>
 		<ul>
           <li>List one in heading two</li>
           <li>List two in heading two</li>
           <li id="list3">List three in heading two</li>
           <li>List four in heading two</li>
           <li>List five in heading two</li>
           <li>List six in heading two</li>
           <li>List seven in heading two</li>
           <li>List eight in heading two</li>
        </ul>
    </div>
 	<div id="headingthree">
 		<h1>Heading Three</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      
        b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem        		Ipsum has been the industry's standard dummy text ever since the 1500s, when an         		unknown printer took a galley of type and scrambled it to make a type specimen            		  book. It has survived not only five centuries, but also the leap into electronic        		  typesetting, remaining essentially unchanged. It was popularised in the 1960s           		  with the release of Letraset sheets containing Lorem Ipsum passages, and more           		  recently with desktop publishing software like Aldus PageMaker including versions         		of Lorem Ipsum.
 		</p>
   </div>
   <h1> Hi There! </h1>
 </body>
</html>

CSS 代码:

button{
 float:right;
 background-color:yellow;
 color:red;
}
a{
 display: block;
}

JavaScript 代码:

let hone = document.querySelector('#heading_one');
let listthree = document.querySelector('#list3');
hone.addEventListener('click', navigatelistthree, false);

function navigatelistthree(e) {
  listthree.scrollIntoView({behavior: 'smooth'});
}

在此示例代码中,querySelector 获取第一个具有 id 属性值为 heading_one 的元素并将其保存到 hone 变量中。之后,它选择第一个具有 id 值的元素作为 list3 并将其存储到名为 listthree 的变量中。

每当你单击 Heading 1 超链接时,navigatelistthree 方法就会执行。此函数将你带到标题 2 下的第三个列表项,写为标题二中的列表三

scrollIntoView 方法可帮助你滚动视图中的元素。它用于你希望突出显示特定元素并希望滚动它的地方。

该方法接受一个参数;它可以是一个布尔值或一个对象

你可以使用 scrollIntoView() 立即跳转到你想要的元素。或者,你可以使用 behavior 属性平滑滚动。

检查此链接以了解有关 scrollIntoView() 函数参数的更多信息。

使用 JavaScript scrollTop 函数滚动到底部

HTML 代码:

<div id="boxcontent">
 <div class="maincontent">
     Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has    		been the industry's standard dummy text ever since the 1500s, when an unknown printer took a  	   galley of type and scrambled it to make a type specimen book. It has survived not only five      centuries, but also the leap into electronic typesetting, remaining essentially unchanged.        It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum        passages, and more recently with desktop publishing software like Aldus PageMaker including      versions of Lorem Ipsum.
   
     Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has    		been the industry's standard dummy text ever since the 1500s, when an unknown printer took a  	   galley of type and scrambled it to make a type specimen book. It has survived not only five      centuries, but also the leap into electronic typesetting, remaining essentially unchanged.        It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum        passages, and more recently with desktop publishing software like Aldus PageMaker including      versions of Lorem Ipsum.
   
     Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has    		been the industry's standard dummy text ever since the 1500s, when an unknown printer took a  	   galley of type and scrambled it to make a type specimen book. It has survived not only five      centuries, but also the leap into electronic typesetting, remaining essentially unchanged.        It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum        passages, and more recently with desktop publishing software like Aldus PageMaker including      versions of Lorem Ipsum.
   
     Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has    		been the industry's standard dummy text ever since the 1500s, when an unknown printer took a  	   galley of type and scrambled it to make a type specimen book. It has survived not only five      centuries, but also the leap into electronic typesetting, remaining essentially unchanged.        It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum        passages, and more recently with desktop publishing software like Aldus PageMaker including      versions of Lorem Ipsum.
   
     Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has    		been the industry's standard dummy text ever since the 1500s, when an unknown printer took a  	   galley of type and scrambled it to make a type specimen book. It has survived not only five      centuries, but also the leap into electronic typesetting, remaining essentially unchanged.        It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum        passages, and more recently with desktop publishing software like Aldus PageMaker including      versions of Lorem Ipsum.
   
     Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has    		been the industry's standard dummy text ever since the 1500s, when an unknown printer took a  	   galley of type and scrambled it to make a type specimen book. It has survived not only five      centuries, but also the leap into electronic typesetting, remaining essentially unchanged.        It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum        passages, and more recently with desktop publishing software like Aldus PageMaker including      versions of Lorem Ipsum.
  </div>
</div>
<button id="button">Scroll to Bottom</button>

CSS 代码:

#boxcontent {
 height: 200px;
 width: 300px;
 overflow: scroll;
 width: 300px;
}
.maincontent {
 width: 100%;
 height: 400px;
}

JavaScript 代码:

document.getElementById('button').addEventListener('click', function() {
  var element = document.getElementById('boxcontent');
  element.scrollTop = element.scrollHeight;
});

首先,如果你单击滚动到底部按钮,则会选择 id 值为按钮的元素。然后,选择 id 属性值为 boxcontent 的另一个元素并将其保存到 element 变量中。

它会将你带到内容框的末尾,该内容框是可滚动的,因为 element.scrollHeight 的值已分配给 element.scrollTop。你可以在此处查看更多详细信息以进行练习。

JavaScript 中名为 scrollTop 的属性设置或获取元素内容垂直滚动的像素数。

如果 non-scrollable 属性与元素相关联,scrollTop 值将为零。或者元素没有溢出。请记住,如果有负值,此属性会将自身设置为 ZERO

使用 JavaScript ScrollingElement 函数滚动到底部

HTML 代码:

<!DOCTYPE html>
<html>
 <head>
 	<title>Scroll Automatically</title>
 </head>
 <body id='main_body'>
 	<button id="bottompage">Bottom</button>
 	<div id="headingone">
 		<h1>Heading One</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-             			technology-background-of-software-developer-picture-id1294521676?                   			b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum 			has been the industry's standard dummy text ever since the 1500s, when an unknown printer 		  took a galley of type and scrambled it to make a type specimen book. It has survived not 		   only five centuries, but also the leap into electronic typesetting, remaining essentially 		 unchanged. It was popularised in the 1960s with the release of Letraset sheets containing 		   Lorem Ipsum passages, and more recently with desktop publishing software like Aldus 				PageMaker including versions of Lorem Ipsum.
 		</p>
   </div>
   <div id="headingtwo">
 		<h1>Heading Two</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      					b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem        	 	Ipsum has been the industry's standard dummy text ever since the 1500s, when an         		unknown printer took a galley of type and scrambled it to make a type specimen book.       		 It has survived not only five centuries, but also the leap into electronic           			typesetting, remaining essentially unchanged. It was popularised in the 1960s with        		  the release of Letraset sheets containing Lorem Ipsum passages, and more recently         		with desktop publishing software like Aldus PageMaker including versions of Lorem         		  Ipsum.
 		</p>
   </div>
   <div id="headingthree">
 		<h1>Heading Three</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      					b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem        		Ipsum has been the industry's standard dummy text ever since the 1500s, when an         		unknown printer took a galley of type and scrambled it to make a type specimen book.       		 It has survived not only five centuries, but also the leap into electronic           			typesetting, remaining essentially unchanged. It was popularised in the 1960s with        		  the release of Letraset sheets containing Lorem Ipsum passages, and more recently         		with desktop publishing software like Aldus PageMaker including versions of Lorem         		  Ipsum.
 		</p>
   </div>
   <h1> Hi There! </h1>
 </body>
</html>

CSS 代码:

button{
 float:right;
 background-color:yellow;
 color:red;
}

JavaScript 代码:

document.querySelector('#bottompage').addEventListener('click', () => {
  var scrollingElement = (document.scrollingElement || document.body);
  scrollingElement.scrollTop = scrollingElement.scrollHeight;
})

上面给出的代码选择带有 id 作为 bottompage 的标签元素。

当你单击 id 值为 bottompage 的元素时,将触发一个事件。之后,根元素(HTML 标签)或 body 标签(任何可用的)的引用保存在名为 scrollingElement 的变量中。

此外,由于将 scrollingElement.scrollHeight 的值分配给 scrollingElement.scrollTopscrollTop 的值从 0px 更改为 1310px

使用 JavaScript scrollBy 函数滚动到底部

HTML 代码:

<!DOCTYPE html>
<html>
 <head>
 	<title>Scroll Automatically</title>
 </head>
 <body id='main_body'>
 	<div id="headingone">
 		<h1>Heading One</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      					b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum      	 has been the industry's standard dummy text ever since the 1500s, when an unknown printer         took a galley of type and scrambled it to make a type specimen book. It has survived not         only five centuries, but also the leap into electronic typesetting, remaining essentially         unchanged. It was popularised in the 1960s with the release of Letraset sheets containing         Lorem Ipsum passages, and more recently with desktop publishing software like Aldus               PageMaker including versions of Lorem Ipsum.
        </p>
   </div>
   <div id="headingtwo">
 		<h1>Heading Two</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      					b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum      	 has been the industry's standard dummy text ever since the 1500s, when an unknown printer         took a galley of type and scrambled it to make a type specimen book. It has survived not         only five centuries, but also the leap into electronic typesetting, remaining essentially         unchanged. It was popularised in the 1960s with the release of Letraset sheets containing         Lorem Ipsum passages, and more recently with desktop publishing software like Aldus               PageMaker including versions of Lorem Ipsum.
        </p>
   </div>
   <div id="headingthree">
 		<h1>Heading Three</h1>
 		<img src="https://media.istockphoto.com/photos/programming-code-abstract-technology-      		  background-of-software-developer-picture-id1294521676?                      					b=1&k=20&m=1294521676&s=170667a&w=0&h=7pqhrZcqqbQq43Q0_TD0Y_YjInAyvA9xiht9bto030U=" 			alt="Programming Picture">
 		<p>
        Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum      	 has been the industry's standard dummy text ever since the 1500s, when an unknown printer         took a galley of type and scrambled it to make a type specimen book. It has survived not         only five centuries, but also the leap into electronic typesetting, remaining essentially         unchanged. It was popularised in the 1960s with the release of Letraset sheets containing         Lorem Ipsum passages, and more recently with desktop publishing software like Aldus               PageMaker including versions of Lorem Ipsum.
 		</p>
  </div>
 </body>
</html>

CSS 代码:

body{
 background-color:lightgray;
}
h1{
 color:red;
}

JavaScript 代码:

let scrollID;
let stopped = true;
let scrollSpeed = 2;  // 1 - Fast | 2 - Medium | 3 - Slow
let scrollInterval = scrollSpeed * 3;

function startScrolling() {
  let ID = setInterval(function() {
    window.scrollBy(0, 2);
    if ((window.innerHeight + window.scrollY) >= document.body.offsetHeight) {
      // Reached end of page
      stopScroll();
    }
  }, scrollInterval);
  return ID;
}

function stopScroll() {
  clearInterval(scrollID);
}

document.body.addEventListener('keypress', function(event) {
  if (event.which == 13 || event.keyCode == 13) {
    // It's the 'Enter' key
    if (stopped == true) {
      scrollID = startScrolling();
      stopped = false;
    } else {
      stopScroll();
      stopped = true;
    }
  }
}, true);

我们在此示例代码中使用了 setInterval 方法中的 scrollBy 函数来为滚动设置动画。

当你希望页面滚动到一定数量的像素时,使用 scrollBy 方法。scrollBy 函数有两个参数,xy(都是必需的)。

setInterval() 方法在给定的时间间隔内调用一个函数。innerHeight 返回窗口的内部高度(以像素为单位)。scrollY 返回 document 现在垂直滚动的像素数。

名为 offsetHeight 的只读属性以整数形式返回元素的高度(在我们的示例中,它是 body 标签)。此高度包括边框和垂直填充。

如果按下 Enter 键,上面的代码会滚动网页。并以两种方式停止滚动,再次按下 Enter 键或 window.innerHeightwindow.scrollY 之和大于或等于 document.body.offsetHeight

作者: Mehvish Ashiq
Mehvish Ashiq avatar Mehvish Ashiq avatar

Mehvish Ashiq is a former Java Programmer and a Data Science enthusiast who leverages her expertise to help others to learn and grow by creating interesting, useful, and reader-friendly content in Computer Programming, Data Science, and Technology.

LinkedIn GitHub Facebook

相关文章 - JavaScript Scroll