ใช้ scroll-behavior: smooth เพื่อการเลื่อนหน้าจอที่นุ่มนวล
CSS property scroll-behavior: smooth ทำให้การกระโดดไปยัง anchor link (เช่น href="#section2") เลื่อนอย่างนุ่มนวล ไม่กระปริบ ทำได้โดยเพียงบรรทัดเดียว ไม่ต้องใช้ JavaScript
โค้ดตัวอย่าง
<!DOCTYPE html>
<html>
<head>
<style>
html {
scroll-behavior: smooth;
}
* {
box-sizing: border-box;
}
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
margin: 0px;
padding: 0px;
}
#firstSection {
height: 100vh;
background-color: rgb(119, 77, 219);
color: white;
padding: 20px;
}
#secondSection {
height: 100vh;
color: white;
background-color: rgb(42, 128, 168);
padding: 20px;
}
a {
text-decoration: none;
font-size: 20px;
font-weight: bold;
color: yellow;
}
</style>
</head>
<body>
<h1>ตัวอย่าง Smooth Scroll</h1>
<div id="firstSection">
<h2>Section 1</h2>
<p>คลิกลิงก์เพื่อดูเอฟเฟกต์ smooth scroll</p>
<a href="#secondSection">คลิกเพื่อเลื่อนไป Section 2</a>
</div>
<div id="secondSection">
<h2>Section 2</h2>
<a href="#firstSection">คลิกเพื่อเลื่อนกลับ Section 1</a>
</div>
</body>
</html>
จุดสำคัญ
- กำหนด
scroll-behavior: smoothที่htmlหรือbody - แต่ละ Section ต้องมี
idที่ตรงกับhrefของลิงก์ - รองรับบราว์เซอร์สมัยใหม่ทั้งหมด (Chrome, Firefox, Safari, Edge)
- ไม่ต้องเขียน JavaScript ลดโค้ดและเพิ่มประสิทธิภาพ
ข้อควรระวัง
ผู้ใช้บางคนอาจชอบการเลื่อนทันที (instant) สามารถเพิ่ม @media (prefers-reduced-motion: reduce) เพื่อปิด smooth scroll ให้ผู้ที่ตั้งค่าลดการเคลื่อนไหวในระบบ