Русские Блоги
window.pageXOffset / pageYOffset и scrollLeft, scrollTop возвращают координаты положения текущей страницы относительно левого верхнего угла области отображения окна
Применение:
Возвращает начальную точку левого верхнего угла окна просмотра веб-страницы относительно позиции браузера X, Y
pageXOffset Устанавливает или возвращает положение X текущей страницы относительно левого верхнего угла области отображения окна.
pageYOffset Устанавливает или возвращает положение Y текущей страницы относительно левого верхнего угла области отображения окна.
window.pageYOffset не работает в iOS7
В приложениях, предшествующих iOS7, это будет работать отлично. Но теперь в моем приложении iOS7 window.pageYOffset постоянно возвращает 0. Есть ли известное решение для этого?
window.pageYOffset работает в браузере Safari, но не в UIWebView
2 ответа
Если вы перезаписали UIScrollViewDelegate в UIWebView?
В iOS7 вам нужно изменить, как это
У меня та же проблема и я отказался от window.pageYOffset в настоящее время под iOS7 — тот же код работал для меня с iOS3!
Мое решение: у меня есть подкласс UIWebView, который я использую, который реализует
Метод и в том, что у меня есть
CGFloat newOffY = scrollView.contentOffset.y + topLength
С topLength, устанавливаемым из содержащего UIViewController через:
Затем вы можете передать newOffY обратно в ваш UIWebView для использования в вашем JavaScript.
Window sizes and scrolling
How do we find the width and height of the browser window? How do we get the full width and height of the document, including the scrolled out part? How do we scroll the page using JavaScript?
For this type of information, we can use the root document element document.documentElement , that corresponds to the <html> tag. But there are additional methods and peculiarities to consider.
Width/height of the window
To get window width and height, we can use the clientWidth/clientHeight of document.documentElement :
For instance, this button shows the height of your window:
Browsers also support properties like window.innerWidth/innerHeight . They look like what we want, so why not to use them instead?
If there exists a scrollbar, and it occupies some space, clientWidth/clientHeight provide the width/height without it (subtract it). In other words, they return the width/height of the visible part of the document, available for the content.
window.innerWidth/innerHeight includes the scrollbar.
If there’s a scrollbar, and it occupies some space, then these two lines show different values:
In most cases, we need the available window width in order to draw or position something within scrollbars (if there are any), so we should use documentElement.clientHeight/clientWidth .
Please note: top-level geometry properties may work a little bit differently when there’s no <!DOCTYPE HTML> in HTML. Odd things are possible.
In modern HTML we should always write DOCTYPE .
Width/height of the document
Theoretically, as the root document element is document.documentElement , and it encloses all the content, we could measure the document’s full size as document.documentElement.scrollWidth/scrollHeight .
But on that element, for the whole page, these properties do not work as intended. In Chrome/Safari/Opera, if there’s no scroll, then documentElement.scrollHeight may be even less than documentElement.clientHeight ! Weird, right?
To reliably obtain the full document height, we should take the maximum of these properties:
Why so? Better don’t ask. These inconsistencies come from ancient times, not a “smart” logic.
Get the current scroll
DOM elements have their current scroll state in their scrollLeft/scrollTop properties.
For document scroll, document.documentElement.scrollLeft/scrollTop works in most browsers, except older WebKit-based ones, like Safari (bug 5991), where we should use document.body instead of document.documentElement .
Luckily, we don’t have to remember these peculiarities at all, because the scroll is available in the special properties, window.pageXOffset/pageYOffset :
These properties are read-only.
For historical reasons, both properties exist, but they are the same:
- window.pageXOffset is an alias of window.scrollX .
- window.pageYOffset is an alias of window.scrollY .
Scrolling: scrollTo, scrollBy, scrollIntoView
To scroll the page with JavaScript, its DOM must be fully built.
For instance, if we try to scroll the page with a script in <head> , it won’t work.
Regular elements can be scrolled by changing scrollTop/scrollLeft .
We can do the same for the page using document.documentElement.scrollTop/scrollLeft (except Safari, where document.body.scrollTop/Left should be used instead).
Alternatively, there’s a simpler, universal solution: special methods window.scrollBy(x,y) and window.scrollTo(pageX,pageY).
The method scrollBy(x,y) scrolls the page relative to its current position. For instance, scrollBy(0,10) scrolls the page 10px down.
The button below demonstrates this:
The method scrollTo(pageX,pageY) scrolls the page to absolute coordinates, so that the top-left corner of the visible part has coordinates (pageX, pageY) relative to the document’s top-left corner. It’s like setting scrollLeft/scrollTop .
To scroll to the very beginning, we can use scrollTo(0,0) .
These methods work for all browsers the same way.
scrollIntoView
For completeness, let’s cover one more method: elem.scrollIntoView(top).
The call to elem.scrollIntoView(top) scrolls the page to make elem visible. It has one argument:
- If top=true (that’s the default), then the page will be scrolled to make elem appear on the top of the window. The upper edge of the element will be aligned with the window top.
- If top=false , then the page scrolls to make elem appear at the bottom. The bottom edge of the element will be aligned with the window bottom.
The button below scrolls the page to position itself at the window top:
And this button scrolls the page to position itself at the bottom:
Forbid the scrolling
Sometimes we need to make the document “unscrollable”. For instance, when we need to cover the page with a large message requiring immediate attention, and we want the visitor to interact with that message, not with the document.
To make the document unscrollable, it’s enough to set document.body.style.overflow = "hidden" . The page will “freeze” at its current scroll position.
The first button freezes the scroll, while the second one releases it.
We can use the same technique to freeze the scroll for other elements, not just for document.body .
The drawback of the method is that the scrollbar disappears. If it occupied some space, then that space is now free and the content “jumps” to fill it.
Размеры окна и позиция прокрутки в JavaScript
В этой теме рассмотрим свойства объекта window, которые предназначены для получения внутренних ( innerWidth , innerHeight ) и внешних ( outerWidth , outerHeight ) размеров окна, его положения относительно экрана ( screenLeft , screenTop ) и координат прокрутки страницы ( pageXOffset и pageYOffset ) в JavaScript.
Свойства innerWidth и innerHeight
innerWidth – это свойство, которое позволяет получить внутреннюю ширину окна в пикселях (включая при этом в этот размер ширину вертикальной полосы прокрутки при её наличии).
innerHeight , в отличие от innerWidth предназначено соответственно для возвращения внутренней высоты окна в пикселях.
Свойства innerWidth и innerHeight доступны только для чтения и не имеют значения по умолчанию.
Если код выполняется в контексте объекта window , то его свойства и методы можно использовать без указания window :
Если вам нужно узнать внутреннюю ширину окна за вычетом ширины его вертикальной полосы прокрутки и любых границ, то используйте свойство clientWidth элемента <html> :
Получение внутренней высоты окна без учёта горизонтальной полосы прокрутки и границ выполняется через clientHeight элемента <html> :
Пример, в котором мы выведем на страницу данные о внутренних размерах окна:
onresize – это свойство, посредством которого мы назначили обработчик для события resize для window .
outerWidth и outerHeight
Свойства « window.outerWidth » и « window.outerHeight » применяются довольно редко. Они предназначены для получения соответственно ширины и высоты всего окна браузера (включая границы самого окна, панель закладок и т.д.).
Пример, в котором мы выведем данные о внешних размерах окна на экран:
screenX и screenY (screenLeft и screenTop)
« window.screenX » и « window.screenY » предназначены для получения положения окна браузера (т.е. его x и y координат) относительно экрана.
В Internet Explorer 8 и более ранних версиях, объект window не содержит свойств screenX и screenY . В них это выполняется через « window.screenLeft » и « window.screenTop ». В то же время Mozilla Firefox (до версии 64) поддерживает только « window.screenX » и « window.screenY ». Остальные браузеры поддерживает как один, так и другой вариант свойств.
Например, выведем координаты окна браузера относительно экрана при клике на ссылку:
scrollX и scrollY (pageXOffset и pageYOffset)
scrollX и scrollY используются, когда нужно получить количество пикселей, на которые документ пролистали в данный момент соответственно по горизонтали и вертикали. Эти свойства доступны только для чтения.
Возвращаемое ими значение является числом с плавающей точкой. Для того чтобы сделать его целочисленным, можно, например, воспользоваться методом Math.round() :
Определить, был ли пролистан контент можно, например так:
Нахождение в переменной hasScrolling значения false будет говорить о том, что контент в данный момент не пролистан, true – в противном случае.
Пример, в котором мы выведем на экран информацию о значениях прокрутки:
onscroll – это свойство, посредством которого мы назначили обработчик для события scroll для window .
Свойства pageXOffset и pageYOffset идентичны соответственно scrollX и scrollY .