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 であるタグ要素を選択します。クリックすると、イベントがトリガーされ、ページの一番下までスクロールします(垂直方向にスクロールします)。これは、x0 に設定され、ydocument.body.scrollHeight1655px)に設定されているためです。

scrollTo 関数は、document を Web ページの指定された座標にスクロールするために使用されます。この方法は、スクロールバーが表示されていて、document が画面に比べて大きい場合に機能します。

scrollTo() メソッドの両方のパラメーターが必要です。パラメータ x は、水平方向にどれだけスクロールするかをピクセル単位で示し、y は垂直方向にピクセル単位でスクロールする量を示します。

あなたは高さの計算方法について考えているかもしれませんか?そのためには、ここを読んで、身長のすべての計算を理解することができます。

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 の下にある見出し 2 のリスト 3 と書かれた 3 番目のリスト項目に移動します。

scrollIntoView メソッドは、ビュー内の要素をスクロールするのに役立ちます。特定の要素を強調表示したり、スクロールしたりする場合に使用します。

このメソッドは 1つのパラメーターを受け入れます。ブール値値またはオブジェクトにすることができます。

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

まず、Scroll to Bottom ボタンをクリックすると、ID の値が button である要素が選択されます。次に、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;
})

上記のコードは、idbottompage として持つタグ要素を選択します。

id の値が bottompage である要素をクリックすると、イベントが発生します。その後、ルート要素(HTML タグ)または body タグ(使用可能なものは何でも)の参照が scrollingElement という名前の変数に保存されます。

さらに、scrollingElement.scrollHeight の値が scrollingElement.scrollTop に割り当てられたため、scrollTop の値が 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 の 2つのパラメーターを取ります(両方とも必須です)。

setInterval() メソッドは、指定された間隔で関数を呼び出します。innerHeight は、ウィンドウの内部の高さ(ピクセル単位)を返します。scrollY は、document が垂直方向にスクロールされたピクセル数を返します。

offsetHeight という名前の読み取り専用プロパティは、要素の高さ(この例では、body タグ)を整数として返します。この高さには、境界線と垂直方向のパディングが含まれます。

上記のコードは、Enterキーが押された場合に Web ページをスクロールします。そして、2つの方法でスクロールを停止します。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