Thuộc tính window.pageXOffset trả về số pixel trang đã cuộn theo chiều ngang (từ góc trái). Chỉ đọc (read-only).
Cú pháp
window.pageXOffset
Ví dụ
<!DOCTYPE html>
<html>
<style>
body { color: #000; height: 100vh; background-color: #8BC6EC; background-image: linear-gradient(135deg, #8BC6EC 0%, #9599E2 100%) no-repeat; text-align: center; }
.btn { background: #db133a; border: none; height: 2rem; border-radius: 2px; width: 40%; display: block; color: #fff; outline: none; cursor: pointer; margin: 1rem auto; }
.box { width: 2000px; height: 1000px; background: teal; color: #fff; font-size: 1.5rem; text-align: left; padding: 20px; }
</style>
<body>
<h1>Demo window.pageXOffset</h1>
<button onclick="scrollRight()" class="btn">Cuộn phải 10px</button>
<button onclick="showOffset()" class="btn">Xem pageXOffset</button>
<div class="box" id="box">Kéo thanh cuộn ngang hoặc bấm nút</div>
<script>
function showOffset() {
document.getElementById('box').innerHTML = 'pageXOffset: ' + window.pageXOffset + 'px';
}
function scrollRight() {
window.scrollBy(10, 0);
}
</script>
</body>
</html>
Kết quả
Nhấn "Xem pageXOffset" → hiển thị pixel đã cuộn ngang. Nhấn "Cuộn phải" vài lần → giá trị tăng dần.
Tương đương: window.scrollX (tên mới, chuẩn hơn). Cặp đôi: pageYOffset / scrollY cho cuộn dọc.