Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

Smooth Scroll ไปด้านล่างสุดหน้า ด้วย JavaScript & CSS

เรียนรู้ smooth scroll ผู้ใช้ไปด้านล่างหน้ายาว ด้วย JS และ CSS นิดหน่อย

ใช้ CSS property scroll-behavior และ JS method scrollIntoView()

ต้องมี:

  • หน้ายาวพอให้มี y-axis scrollbar
  • Anchor element ที่บนสุดมี id
  • Element ใดๆ ที่ล่างสุดมี id
  • scroll-behavior CSS property
  • scrollIntoView() JS property

HTML Layout Example

<main>
  <p><a id="scroll-to-bottom">Scroll to bottom</a></p>
  <p>....</p> (หลายบรรทัด)
  <p id="page-bottom">You have reached the bottom of this page!!</p>
</main>

CSS

html {
  scroll-behavior: smooth;
}
main {
  max-width: 700px;
  margin: 3rem auto;
  padding: 0 1rem;
}
#scroll-to-bottom {
  font-weight: bold;
  color: green;
}

Scroll magic มาจาก scroll-behavior: smooth; ส่วนที่เหลือ cosmetic

JavaScript

let scrollToBottom = document.querySelector("#scroll-to-bottom");
let pageBottom = document.querySelector("#page-bottom");
scrollToBottom.addEventListener("click", function() {
  pageBottom.scrollIntoView();
});

JS ทำงานอย่างไร

  • Declare 2 variables reference scroll-to-bottom และ page-bottom
  • Attach event listener listen click events
  • ใน function เรียก scrollIntoView() บน pageBottom element

คลิก scroll to bottom → scroll ไป id page-bottom

Note: ลบ scroll-behavior: smooth; scroll ยังทำงานแต่ abrupt

Pure vanilla JS smooth scroll ได้แต่ code ยาวกว่ามาก

ดู demo code ทั้งหมด

ประโยชน์ในชีวิตจริง

Use case: ให้ visitor scroll เร็วไป summary ของเนื้อหายาวที่ไม่อ่านหมดทัน

Browser Compatibility

scroll-behavior ไม่รองรับ IE และ Safari ต้องใช้ pure JS solution แทน