Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

266
Vistas
Javascript to calculate pixel distance between top of div and top of document

As the title says, is there any function or simple method to calculate pixel distance between the top of a div and the top of the HTML document? All the questions I've seen on stackoverflow do it for top of div and top of viewport which is different than what I need. Thanks in advance.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

Here is a function you could use, but I'm not sure it works on all contexts :

function topRelativeToDocumentElement(element) {
    var curCss, t=0;
    while (element!==null && element!==document.documentElement) {
        if ((defaultView=element.ownerDocument.defaultView) && (computedStyle=defaultView.getComputedStyle(element, null))) {
            curCss=computedStyle.getPropertyValue("position");
        } else {
            curCss=null;
        }
        if (curCss!=="static" && curCss!=="fixed") {
            t+=element.offsetTop;
        } else if (curCss==="fixed") {
            t+=element.offsetTop;
            break;
        }
        if (typeof(element.parentNode)!=="undefined") {
            element=element.parentNode;
        } else {
            break;
        }
    }
    return t;
}

[Edit] I would advise to use this instead :

var top=elem.getBoundingClientRect().top - document.documentElement.getBoundingClientRect().top

The first function takes not in consideration css transforms, the second one does.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda