วิธีการ - เลื่อนอย่างราบรื่น
เรียนรู้วิธีสร้างเอฟเฟกต์การเลื่อนที่ราบรื่นด้วย CSS
เลื่อนเรียบ
ส่วนที่ 1
คลิกที่ลิงค์เพื่อดูเอฟเฟกต์การเลื่อนที่ "ราบรื่น"
คลิกฉันเพื่อเลื่อนไปที่ส่วนที่ 2 ด้านล่างอย่างราบรื่นหมายเหตุ: ลบคุณสมบัติการเลื่อนเพื่อลบการเลื่อนอย่างราบรื่น
เลื่อนเรียบ
เพิ่มscroll-behavior: smooth
ในองค์ประกอบ <html> เพื่อเปิดใช้งานการเลื่อนอย่างราบรื่นสำหรับทั้งหน้า (หมายเหตุ: คุณสามารถเพิ่มไปยังองค์ประกอบ/คอนเทนเนอร์การเลื่อนเฉพาะได้):
ตัวอย่าง
html {
scroll-behavior: smooth;
}
รองรับเบราว์เซอร์
ตัวเลขในตารางระบุเบราว์เซอร์รุ่นแรกที่สนับสนุนคุณสมบัติพฤติกรรมการเลื่อนอย่างเต็มที่
Property | |||||
---|---|---|---|---|---|
scroll-behavior | 61.0 | 79.0 | 36.0 | 14.0 | 48.0 |
โซลูชันข้ามเบราว์เซอร์
สำหรับเบราว์เซอร์ที่ไม่รองรับscroll-behavior
คุณสมบัติ คุณสามารถใช้ JavaScript หรือไลบรารี JavaScript เช่นjQueryเพื่อสร้างโซลูชันที่จะใช้ได้กับทุกเบราว์เซอร์:
ตัวอย่าง
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Add smooth scrolling to all
links
$("a").on('click', function(event) {
// Make sure this.hash
has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
//
Store hash
var hash = this.hash;
// Using jQuery's animate() method
to add smooth page scroll
// The optional number (800) specifies the number
of milliseconds it takes to scroll to the specified area
$('html,
body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
เคล็ดลับ:อ่านเพิ่มเติมเกี่ยวกับคุณสมบัติ scroll-behavior ในการอ้างอิง CSS ของเรา: คุณสมบัติ การเลื่อน CSS