Как определить, прокручивает ли окно "html" или "body" - PullRequest
6 голосов
/ 14 мая 2010

Код ниже используется для поиска элемента, который можно прокручивать (текст или html) через javascript.

    var scrollElement = (function (tags) {
        var el, $el, init;
        // iterate through the tags...
        while (el = tags.pop()) {
            $el = $(el);
            // if the scrollTop value is already > 0 then this element will work
            if ( $el.scrollTop() > 0){
                return $el;
            }
            // if scrollTop is 0 try to scroll.
            else if($el.scrollTop( 1 ).scrollTop() > 0) {
                // if that worked reset the scroll top and return the element
                return $el.scrollTop(0);
            }
        }
        return $();
    } (["html", "body"]));

    // do stuff with scrollElement...like:
    // scrollElement.animate({"scrollTop":target.offset().top},1000);

Этот код отлично работает, когда высота document больше, чем высота window. Однако, когда высота document равна или меньше window, приведенный выше метод будет не работать, потому что scrollTop() всегда будет равен 0. Это становится проблемой, если DOM обновляется, и высота document становится больше высоты window после выполнения кода.

Кроме того, я обычно не жду до тех пор, пока document.ready настроит мои обработчики javascript (это обычно работает). Я мог бы временно добавить высокий div к body, чтобы заставить вышеуказанный метод работать, НО, который потребовал бы готовности документа в IE (вы не можете добавить узел к элементу тела до тег закрыт). Подробнее о теме document.ready «anti-pattern» читайте здесь .

Итак, я бы хотел найти решение, которое находит прокручиваемый элемент, даже если document короткое. Есть идеи?

1 Ответ

9 голосов
/ 27 апреля 2015

Прошло около 5 лет с тех пор, как я спросил это ... но лучше поздно, чем никогда!

document.scrollingElement теперь является частью спецификации CSSOM, но на данный момент практически не имеет практической реализации браузера (апрель 2015 г.). Тем не менее, вы все равно можете найти элемент ...

Используя этот полифилл , Матиас Биненс и Диего Перини .

Который реализует это базовое решение Диего Перини (приведенный выше полифил лучше и совместим с CSSOM, поэтому вам, вероятно, следует его использовать.):

/*
 * How to detect which element is the scrolling element in charge of scrolling the viewport:
 *
 * - in Quirks mode the scrolling element is the "body"
 * - in Standard mode the scrolling element is the "documentElement"
 *
 * webkit based browsers always use the "body" element, disrespectful of the specifications:
 *
 *  http://dev.w3.org/csswg/cssom-view/#dom-element-scrolltop
 *
 * This feature detection helper allow cross-browser scroll operations on the viewport,
 * it will guess which element to use in each browser both in Quirk and Standard modes.
 * See how this can be used in a "smooth scroll to anchors references" example here:
 *
 *  https://dl.dropboxusercontent.com/u/598365/scrollTo/scrollTo.html
 *
 * It is just a fix for possible differences between browsers versions (currently any Webkit).
 * In case the Webkit bug get fixed someday, it will just work if they follow the specs. Win !
 *
 * Author: Diego Perini
 * Updated: 2014/09/18
 * License: MIT
 *
 */
function getScrollingElement() {
  var d = document;
  return  d.documentElement.scrollHeight > d.body.scrollHeight &&
          d.compatMode.indexOf('CSS1') == 0 ?
          d.documentElement :
          d.body;
}

- getScrollingElement.js

...