JavaScript: The Definitive Guide, Sixth Editio javaScript权威指南(第6版) pdf 文字版-文字版, javascript电子书, 和javascript 有关的电子书:

15.8.4 Scrolling

15.8.4 Scrolling

Example 15-8 showed how to query the scrollbar positions for a browser window. The scrollLeft and scrollTop properties used in that example can be set to make the browser scroll, but there is an easier way that has been supported since the earliest days of JavaScript. The scrollTo() method of the Window object (and its synonym scroll()) takes the X and Y coordinates of a point (in document coordinates) and sets these as the scrollbar offsets. That is, it scrolls the window so that the specified point is in the upper left corner of the viewport. If you specify a point that is too close to the bottom or too close to the right edge of the document, the browser will move it as close as possible to the upper left corner but won’t be able to get it all the way there. The

15.8 Document and Element Geometry and Scrolling | 393

following code scrolls the browser so that the bottom-most page of the document is visible:

// Get the height of the document and viewport. offsetHeight is explained below. var documentHeight = document.documentElement.offsetHeight; var viewportHeight = window.innerHeight; // Or use getViewportSize() above // And scroll so the last "page" shows in the viewport window.scrollTo(0, documentHeight - viewportHeight);

The scrollBy() method of the Window is similar to scroll() and scrollTo(), but its arguments are relative and are added to the current scrollbar offsets. Speed readers might like a bookmarklet ( § ) like this one, for example:

// Scroll 10 pixels down every 200 ms. Note there is no way to turn this off! javascript:void setInterval(function() {scrollBy(0,10)}, 200);

Often, instead of scrolling to a numeric location in document, we just want to scroll so that a certain element in the document is visible. You could compute the position of the element with getBoundingClientRect(), convert that position to document coordinates, and then use the scrollTo() method, but it is easier to just call the scrollInto View() method on the desired HTML element. This method ensures that the element on which it is invoked is visible in the viewport. By default, it tries to put the top edge of the element at or near the top of the viewport. If you pass falseas the only argument, it will try to put the bottom edge of the element at the bottom of the viewport. The browser will also scroll the viewport horizontally as needed to make the element visible.

友情链接It题库(| 版权归yishouce.com所有| 友链等可联系|粤ICP备16001685号-1