เลื่อนหน้าต่างX
ตัวอย่าง 1
เลื่อนเนื้อหาไป 100 พิกเซล และเตือน scrollX และ scrollY:
window.scrollBy(100, 100);
alert(window.scrollX + window.scrollY);
ตัวอย่างเพิ่มเติมด้านล่าง
ความหมายและการใช้งาน
คุณสมบัติscrollX
ส่งคืนพิกเซลที่เอกสารเลื่อนจากมุมซ้ายบนของหน้าต่าง
คุณสมบัติscrollX
เป็นแบบอ่านอย่างเดียว
บันทึก
ทรัพย์สินมี ค่าscrollX
เท่ากับ
pageXOffset
ทรัพย์สิน
สำหรับความเข้ากันได้ข้ามเบราว์เซอร์ ให้ใช้ window.pageXOffset แทน window.scrollX
ดูสิ่งนี้ด้วย:
ไวยากรณ์
window.scrollX
หรือเพียงแค่:
scrollX
คืนมูลค่า
พิมพ์ | คำอธิบาย |
หมายเลข | จำนวนพิกเซลที่เอกสารเลื่อนจากมุมซ้ายบนของหน้าต่าง |
ตัวอย่างเพิ่มเติม
สร้างแถบการนำทางที่ติดหนึบ:
// Get the navbar
const navbar = document.getElementById("navbar");
// Get the offset position of the navbar
const sticky = navbar.offsetTop;
// Add the sticky class to the navbar when you reach its scroll position. Remove the sticky class when you leave the scroll position.
function myFunction() {
if (window.scrollY >= sticky) {
navbar.classList.add("sticky")
}
else {
navbar.classList.remove("sticky");
}
}
รองรับเบราว์เซอร์
window.scrollX
รองรับในทุกเบราว์เซอร์:
Chrome | IE | Edge | Firefox | Safari | Opera |
Yes | 9-11 | Yes | Yes | Yes | Yes |