2010-05-14 12 views
6

El siguiente código se usa para buscar el elemento que se puede desplazar (body o html) a través de javascript.Cómo determinar si "html" o "body" se desplaza por la ventana

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); 

Este código funciona perfectamente cuando la altura de la document es mayor que la altura de la window. Sin embargo, cuando la altura del document es igual o menor que window, el método anterior no funcionará porque scrollTop() siempre será igual a 0. Esto se convierte en un problema si el DOM se actualiza y la altura del document crece más allá la altura del window después de ejecutar el código.

Además, por lo general, no espero hasta que esté listo el documento para configurar mis controladores de Javascript (esto generalmente funciona). I podría agregar un div alto al body temporalmente para forzar el método anterior para que funcione PERO eso requeriría que el documento esté listo en IE (no se puede agregar un nodo al elemento del cuerpo antes de que se cierre la etiqueta). Para obtener más información sobre el tema document.ready "antipatrón" read this.

Entonces, me encantaría encontrar una solución que encuentre el elemento desplazable incluso cuando el document es corto. ¿Algunas ideas?

+0

por qué no usar si ($ EL .scrollTop()> = 0)? EDITAR: wow me acabo de dar cuenta de que esta pregunta es muy vieja –

Respuesta

7

Han pasado unos 5 años desde que pregunté esto .... pero mejor tarde que nunca!

document.scrollingElement ahora es parte de la especificación de CSSOM, pero tiene poca o ninguna implementación de navegador en el mundo real en este momento (abril de 2015). Sin embargo, aún puede encontrar el elemento ...

Al usar this polyfill por Mathias Bynens y Diego Perini.

que implementa esta solución básica por Diego Perini (El polyfill anterior es mejor y compatible CSSOM, por lo que probablemente debería usarla.):

/* 
* 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

Cuestiones relacionadas