ตัวอย่างโค้ด
นี่คือตัวอย่างการใช้ jQuery เพื่อสร้างการเลื่อนหน้าจอ (scroll) ไปยังตำแหน่งด้านบนสุดของหน้าเว็บอย่างนุ่มนวลเมื่อคลิกลิงก์
<html>
<body>
<script>
$("a").click(function() {
$("html, body").animate({ scrollTop: 0 }, "slow");
return false;
});
</script>
<h3>TOP OF PAGE</h3>
<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
This is demo text.<br>
<h3>BOTTOM OF PAGE</h3>
<a href="#">Scroll up</a>
</body>
</html>
คำอธิบาย
โค้ดด้านบนใช้ jQuery animate() เพื่อเลื่อน scrollTop ไปที่ 0 (ด้านบนสุด) ด้วยความเร็ว "slow" เมื่อผู้ใช้คลิกที่แท็ก <a> คำสั่ง return false; จะป้องกันไม่ให้ลิงก์ทำงานตามปกติ (ไม่跳转ไป #)
วิธีทำแบบ JavaScript แบบดั้งเดิม (Vanilla JS)
หากไม่ต้องการใช้ jQuery สามารถใช้ window.scrollTo() หรือ element.scrollIntoView() ได้ดังนี้:
// วิธีที่ 1: ใช้ window.scrollTo
document.querySelector('a').addEventListener('click', function(e) {
e.preventDefault();
window.scrollTo({ top: 0, behavior: 'smooth' });
});
// วิธีที่ 2: ใช้ scrollIntoView
document.querySelector('a').addEventListener('click', function(e) {
e.preventDefault();
document.documentElement.scrollIntoView({ behavior: 'smooth' });
});