Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

265
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda