只读 Window property pageYOffset 是别名化的 scrollY ; as such, it returns the number of pixels the document is currently scrolled along the vertical axis (that is, up or down) with a value of 0.0, indicating that the top edge of the Document is currently aligned with the top edge of the window's content area.

There is slightly better support for pageYOffset than for scrollY in older browsers, but if you're not concerned about browsers more than a handful of years old, you can use either one.

The corresponding pageXOffset property, which returns the number of pixels scrolled along the horizontal axis (left and right), is an alias for scrollX .

句法

yOffset = window.pageYOffset;
					

A floating-point number specifying the number of pixels the Document is scrolled vertically within its containing Window . This number is subpixel precise, so it may not be an integer. A value of 0.0 indicates that the window is not scrolled vertically, and that the top of the document is located at the top edge of the window's content area.

Since this property is an alias for Window.scrollY , see that article for additional details on this value and its use.

范例

var contentHTML = `
    <h2 id="introduction">Introduction</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Aenean volutpat vitae felis non dictum. Ut auctor
eros tortor, vel elementum arcu rhoncus nec. Donec non
laoreet massa. Donec pretium nisi et condimentum convallis.
Nullam dictum molestie finibus. Nullam vitae lorem non
augue mattis cursus.</p>
  <p>Maecenas nec tortor tincidunt, sollicitudin mi eget,
fermentum turpis. Vestibulum ac ante et libero efficitur
faucibus id eget ex. Pellentesque tempor pharetra
tincidunt. Suspendisse potenti. Nulla vulputate nunc sit
amet hendrerit faucibus. Nullam metus dui, venenatis
lacinia nunc nec, vestibulum viverra nunc. Quisque interdum
quam tortor, sit amet varius neque consectetur at. Quisque
vel turpis justo.</p>
  <h2 id="overview">Overview</h2>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing
elit. Etiam dui dolor, pulvinar sed diam id, eleifend
dapibus odio. Duis vitae ante nibh. Integer bibendum
imperdiet suscipit. Fusce ligula leo, consectetur ac ante
eget, gravida laoreet purus. Cras sodales efficitur risus,
sed feugiat sem. Pellentesque justo augue, placerat non leo
sit amet, laoreet fringilla arcu.</p>
  <p>Class aptent taciti sociosqu ad litora torquent per
conubia nostra, per inceptos himenaeos. Proin in gravida
libero. Vivamus placerat, lacus eget condimentum sagittis,
enim nunc bibendum nisi, quis varius erat felis sit amet
risus.</p>
<p>Sed non finibus ligula. Fusce a magna auctor, molestie
nibh eget, sodales felis. Donec imperdiet facilisis mi ut
aliquam. Etiam sodales suscipit urna, eget hendrerit neque
elementum a. Vivamus fringilla sodales est ut ultricies.
Nulla convallis congue maximus. Nullam consectetur felis
vitae ultricies accumsan. Mauris at aliquam felis. Mauris
efficitur tellus massa, id ullamcorper ipsum fermentum eu.
Aenean mollis dignissim ultrices. Nunc gravida, sem sit
amet lobortis iaculis, dolor ligula convallis nibh, id
condimentum metus libero nec odio. Quisque nec ante
pretium, viverra neque nec, facilisis risus. Duis
condimentum sapien non felis cursus blandit. Integer
euismod lectus a ipsum pellentesque lacinia.</p>
`;
document.getElementById("frame").contentDocument
        .body.innerHTML = contentHTML;
					

在此范例中, <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 .

HTML

The HTML is extremely simple and has just two elements: an <iframe> that contains the document we're going to scroll, and a <div> into which we'll output the value of pageYOffset when we've finished the scroll.

<iframe id="frame">
</iframe>
<div id="info">
</div>
					

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 offset after scrolling: " +
                 frame.contentWindow.pageYOffset + " pixels";
					

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 .

With the target element in hand, we set the scrollTop of the frame's scrollingElement 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.

CSS

iframe {
  width: 620px;
  height: 450px;
  border: 1px solid black;
}
#info {
  margin-top: 20px;
  font: 16px "Open Sans", "Helvetica", "Arial";
}
					

结果

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.

规范

规范 状态 注释
CSSOM (CSS 对象模型) 视图模块
The definition of 'window.pageYOffset' in that specification.
工作草案

浏览器兼容性

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request. 更新 GitHub 上的兼容性数据
桌面 移动
Chrome Edge Firefox Internet Explorer Opera Safari Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
pageYOffset Chrome 1 Edge 12 Firefox 1 IE 9 Opera 3 Safari 1 WebView Android 1 Chrome Android 18 Firefox Android 4 Opera Android 10.1 Safari iOS 1 Samsung Internet Android 1.0

图例

完整支持

完整支持

另请参阅

元数据

  • 最后修改:
  1. Window
  2. 特性
    1. applicationCache
    2. caches
    3. closed
    4. console
    5. controllers
    6. crossOriginIsolated
    7. crypto
    8. customElements
    9. defaultStatus
    10. devicePixelRatio
    11. dialogArguments
    12. 目录
    13. document
    14. event
    15. frameElement
    16. frames
    17. fullScreen
    18. history
    19. indexedDB
    20. innerHeight
    21. innerWidth
    22. isSecureContext
    23. isSecureContext
    24. length
    25. localStorage
    26. location
    27. locationbar
    28. menubar
    29. mozAnimationStartTime
    30. mozInnerScreenX
    31. mozInnerScreenY
    32. mozPaintCount
    33. 名称
    34. navigator
    35. onabort
    36. onafterprint
    37. onanimationcancel
    38. onanimationend
    39. onanimationiteration
    40. onappinstalled
    41. onauxclick
    42. onbeforeinstallprompt
    43. onbeforeprint
    44. onbeforeunload
    45. onblur
    46. oncancel
    47. oncanplay
    48. oncanplaythrough
    49. onchange
    50. onclick
    51. onclose
    52. oncontextmenu
    53. oncuechange
    54. ondblclick
    55. ondevicelight
    56. ondevicemotion
    57. ondeviceorientation
    58. ondeviceorientationabsolute
    59. ondeviceproximity
    60. ondragdrop
    61. ondurationchange
    62. onended
    63. onerror
    64. onfocus
    65. onformdata
    66. ongamepadconnected
    67. ongamepaddisconnected
    68. ongotpointercapture
    69. onhashchange
    70. oninput
    71. oninvalid
    72. onkeydown
    73. onkeypress
    74. onkeyup
    75. onlanguagechange
    76. onload
    77. onloadeddata
    78. onloadedmetadata
    79. onloadend
    80. onloadstart
    81. onlostpointercapture
    82. onmessage
    83. onmessageerror
    84. onmousedown
    85. onmouseenter
    86. onmouseleave
    87. onmousemove
    88. onmouseout
    89. onmouseover
    90. onmouseup
    91. onmozbeforepaint
    92. onpaint
    93. onpause
    94. onplay
    95. onplaying
    96. onpointercancel
    97. onpointerdown
    98. onpointerenter
    99. onpointerleave
    100. onpointermove
    101. onpointerout
    102. onpointerover
    103. onpointerup
    104. onpopstate
    105. onrejectionhandled
    106. onreset
    107. onresize
    108. onscroll
    109. onselect
    110. onselectionchange
    111. onselectstart
    112. onstorage
    113. onsubmit
    114. ontouchcancel
    115. ontouchstart
    116. ontransitioncancel
    117. ontransitionend
    118. onunhandledrejection
    119. onunload
    120. onuserproximity
    121. onvrdisplayactivate
    122. onvrdisplayblur
    123. onvrdisplayconnect
    124. onvrdisplaydeactivate
    125. onvrdisplaydisconnect
    126. onvrdisplayfocus
    127. onvrdisplaypointerrestricted
    128. onvrdisplaypointerunrestricted
    129. onvrdisplaypresentchange
    130. onwheel
    131. opener
    132. origin
    133. outerHeight
    134. outerWidth
    135. pageXOffset
    136. pageYOffset
    137. parent
    138. 性能
    139. personalbar
    140. pkcs11
    141. screen
    142. screenLeft
    143. screenTop
    144. screenX
    145. screenY
    146. scrollbars
    147. scrollMaxX
    148. scrollMaxY
    149. scrollX
    150. scrollY
    151. self
    152. sessionStorage
    153. sidebar
    154. speechSynthesis
    155. status
    156. statusbar
    157. toolbar
    158. top
    159. visualViewport
    160. window
  3. 方法
    1. alert()
    2. atob()
    3. back()
    4. blur()
    5. btoa()
    6. cancelAnimationFrame()
    7. cancelIdleCallback()
    8. captureEvents()
    9. clearImmediate()
    10. clearInterval()
    11. clearTimeout()
    12. close()
    13. confirm()
    14. convertPointFromNodeToPage()
    15. convertPointFromPageToNode
    16. createImageBitmap()
    17. dump()
    18. fetch()
    19. find()
    20. focus()
    21. forward()
    22. getAttention()
    23. getComputedStyle()
    24. getDefaultComputedStyle()
    25. getSelection()
    26. home()
    27. matchMedia()
    28. minimize()
    29. moveBy()
    30. moveTo()
    31. open()
    32. openDialog()
    33. postMessage()
    34. print()
    35. prompt()
    36. queueMicrotask()
    37. releaseEvents()
    38. requestAnimationFrame()
    39. requestFileSystem()
    40. requestIdleCallback()
    41. resizeBy()
    42. resizeTo()
    43. restore()
    44. routeEvent()
    45. scroll()
    46. scrollBy()
    47. scrollByLines()
    48. scrollByPages()
    49. scrollTo()
    50. setCursor()
    51. setImmediate()
    52. setInterval()
    53. setTimeout()
    54. showModalDialog()
    55. sizeToContent()
    56. stop()
    57. updateCommands()
  4. 事件
    1. event
    2. afterprint
    3. animationcancel
    4. animationend
    5. animationiteration
    6. beforeprint
    7. beforeunload
    8. blur
    9. copy
    10. cut
    11. DOMContentLoaded
    12. error
    13. focus
    14. hashchange
    15. languagechange
    16. load
    17. message
    18. messageerror
    19. offline
    20. online
    21. orientationchange
    22. pagehide
    23. pageshow
    24. paste
    25. popstate
    26. rejectionhandled
    27. storage
    28. transitioncancel
    29. unhandledrejection
    30. unload
    31. vrdisplayconnect
    32. vrdisplaydisconnect
    33. vrdisplaypresentchange