Window.pageYOffset
Window
인터페이스의 pageYOffset
읽기 전용 속성은 scrollY
의 다른 이름으로, 문서가 수직으로 얼마나 스크롤됐는지 픽셀 단위로 반환합니다.
일부 오래된 브라우저는 scrollY
대신 pageYOffset
만 지원하는 경우가 있지만, 노후 환경을 신경쓰지 않아도 된다면 둘 중 아무거나 사용해도 괜찮습니다.
수평 스크롤을 나타내는 pageXOffset
(en-US) 속성 역시 scrollX
의 다른 이름입니다.
구문
yOffset = window.pageYOffset;
값
Window
안의 Document
가 수직 방향으로 스크롤된 거리를 픽셀 단위로 나타낸 부동소숫점 수. 단일 픽셀보다 높은 수준의 정밀도를 가지므로 정수가 아닐 수 있습니다. 0.0
은 창의 콘텐츠 영역과 문서의 위쪽 모서리 위치가 일치함을 나타냅니다.
pageYOffset
은 Window.scrollY
의 다른 이름이므로, 값에 대한 더 자세한 정보는 해당 문서를 방문해주세요.
예제
In this example, an <iframe>
is created and filled with content, then a specific element within the document is scrolled into view in the frame. Once that's done, the vertical scroll position is checked by looking at the value of pageYOffset
in the frame's contentWindow
(en-US).
HTML
JavaScript
var frame = document.getElementById("frame");
var frameDoc = frame.contentDocument;
var info = document.getElementById("info");
var target = frameDoc.getElementById("overview");
frameDoc.scrollingElement.scrollTop = target.offsetTop;
info.innerText = "스크롤 후 Y축 차이: " +
frame.contentWindow.pageYOffset + " 픽셀";
The JavaScript code begins by getting into frame
and info
the <iframe>
element that contains our content as well as the <div>
element into which we'll output the result of our scroll position check. It then gets a reference to the element we want to scroll into view calling getElementById()
on the frame's HTMLIFrameElement.contentDocument
(en-US).
With the target element in hand, we set the scrollTop
(en-US) of the frame's scrollingElement
(en-US) to the offsetTop
of the target element. By doing so, we set the vertical scrolling position of the frame's document so that it's the same as the top edge of the target element.
This will automatically set the scrolling position to the maximum possible value if the attempted scroll would exceed the maximum. This prevents us from falling off the edge of the document. Nobody wants to know what's out there. There might be dragons.
결과
The result follows. Note that the frame's contents have been scrolled to show the section named "Overview", and that the value of the pageYOffset
property is shown with the corresponding value.
명세
Specification |
---|
CSSOM View Module # dom-window-pageyoffset |
브라우저 호환성
BCD tables only load in the browser