只读
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
.
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>
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.
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. |
工作草案 |
| 桌面 | 移动 | |||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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 |
完整支持
pageXOffset
scrollY
and
scrollX
scroll()
,
scrollBy()
,和
scrollTo()
Window
applicationCache
caches
closed
console
controllers
crossOriginIsolated
crypto
customElements
defaultStatus
devicePixelRatio
dialogArguments
目录
document
event
frameElement
frames
fullScreen
history
indexedDB
innerHeight
innerWidth
isSecureContext
isSecureContext
length
localStorage
location
locationbar
menubar
mozAnimationStartTime
mozInnerScreenX
mozInnerScreenY
mozPaintCount
名称
navigator
onabort
onafterprint
onanimationcancel
onanimationend
onanimationiteration
onappinstalled
onauxclick
onbeforeinstallprompt
onbeforeprint
onbeforeunload
onblur
oncancel
oncanplay
oncanplaythrough
onchange
onclick
onclose
oncontextmenu
oncuechange
ondblclick
ondevicelight
ondevicemotion
ondeviceorientation
ondeviceorientationabsolute
ondeviceproximity
ondragdrop
ondurationchange
onended
onerror
onfocus
onformdata
ongamepadconnected
ongamepaddisconnected
ongotpointercapture
onhashchange
oninput
oninvalid
onkeydown
onkeypress
onkeyup
onlanguagechange
onload
onloadeddata
onloadedmetadata
onloadend
onloadstart
onlostpointercapture
onmessage
onmessageerror
onmousedown
onmouseenter
onmouseleave
onmousemove
onmouseout
onmouseover
onmouseup
onmozbeforepaint
onpaint
onpause
onplay
onplaying
onpointercancel
onpointerdown
onpointerenter
onpointerleave
onpointermove
onpointerout
onpointerover
onpointerup
onpopstate
onrejectionhandled
onreset
onresize
onscroll
onselect
onselectionchange
onselectstart
onstorage
onsubmit
ontouchcancel
ontouchstart
ontransitioncancel
ontransitionend
onunhandledrejection
onunload
onuserproximity
onvrdisplayactivate
onvrdisplayblur
onvrdisplayconnect
onvrdisplaydeactivate
onvrdisplaydisconnect
onvrdisplayfocus
onvrdisplaypointerrestricted
onvrdisplaypointerunrestricted
onvrdisplaypresentchange
onwheel
opener
origin
outerHeight
outerWidth
pageXOffset
pageYOffset
parent
性能
personalbar
pkcs11
screen
screenLeft
screenTop
screenX
screenY
scrollbars
scrollMaxX
scrollMaxY
scrollX
scrollY
self
sessionStorage
sidebar
speechSynthesis
status
statusbar
toolbar
top
visualViewport
window
alert()
atob()
back()
blur()
btoa()
cancelAnimationFrame()
cancelIdleCallback()
captureEvents()
clearImmediate()
clearInterval()
clearTimeout()
close()
confirm()
convertPointFromNodeToPage()
convertPointFromPageToNode
createImageBitmap()
dump()
fetch()
find()
focus()
forward()
getAttention()
getComputedStyle()
getDefaultComputedStyle()
getSelection()
home()
matchMedia()
minimize()
moveBy()
moveTo()
open()
openDialog()
postMessage()
print()
prompt()
queueMicrotask()
releaseEvents()
requestAnimationFrame()
requestFileSystem()
requestIdleCallback()
resizeBy()
resizeTo()
restore()
routeEvent()
scroll()
scrollBy()
scrollByLines()
scrollByPages()
scrollTo()
setCursor()
setImmediate()
setInterval()
setTimeout()
showModalDialog()
sizeToContent()
stop()
updateCommands()
event
afterprint
animationcancel
animationend
animationiteration
beforeprint
beforeunload
blur
copy
cut
DOMContentLoaded
error
focus
hashchange
languagechange
load
message
messageerror
offline
online
orientationchange
pagehide
pageshow
paste
popstate
rejectionhandled
storage
transitioncancel
unhandledrejection
unload
vrdisplayconnect
vrdisplaydisconnect
vrdisplaypresentchange