sirve que para obtener elemento ejemplos ejemplo div contenido javascript

que - obtener contenido de un div javascript



¿Cómo obtener la altura de todo el documento con JavaScript? (12)

Ahora no sé cómo determinar la altura, pero puedes usar esto para poner algo en la parte inferior:

<html> <head> <title>CSS bottom test</title> <style> .bottom { position: absolute; bottom: 1em; left: 1em; } </style> </head> <body> <p>regular body stuff.</p> <div class=''bottom''>on the bottom</div> </body> </html>

Algunos documentos no puedo obtener la altura del documento (para colocar algo absolutamente en la parte inferior). Además, un fondo de relleno parece no hacer nada en estas páginas, pero sí en las páginas donde la altura volverá. Caso (s) en el punto:

http://fandango.com/
http://paperbackswap.com/

En fandango
jQuery''s $(document).height(); devuelve el valor correcto
document.height devuelve 0
document.body.scrollHeight devuelve 0

En el intercambio de libros de bolsillo:
jQuery''s $(document).height(); TypeError: $(document) es nulo
document.height devuelve un valor incorrecto
document.body.scrollHeight devuelve un valor incorrecto

Nota: Tengo permisos de nivel de navegador, si hay algún truco allí.


El "método jQuery" para determinar el tamaño del documento (consultar todo, obtener el mayor valor y esperar lo mejor) funciona en la mayoría de los casos, pero no en todos .

Si realmente necesita resultados a prueba de balas para el tamaño del documento, le sugiero que use mi complemento jQuery.documentSize . A diferencia de los otros métodos, en realidad prueba y evalúa el comportamiento del navegador cuando se carga y, según el resultado, consulta la propiedad correcta de ahí en adelante.

El impacto de esta prueba única en el rendimiento es mínimo , y el complemento devuelve los resultados correctos incluso en los escenarios más extraños, no porque yo lo diga, sino porque un conjunto de pruebas masivo y generado automáticamente verifica que así sea.

Debido a que el complemento está escrito en Javascript de vainilla, también puede usarlo sin jQuery .


Esta es una pregunta muy antigua, y por lo tanto, tiene muchas respuestas desactualizadas. A partir de 2017 todos los navegadores se han adherido a la norma.

Respuesta para 2017:

document.body.scrollHeight

Edición: lo anterior no tiene en cuenta los márgenes de la etiqueta <body> . Si tu cuerpo tiene márgenes, usa:

document.documentElement.scrollHeight


Este código de navegador cruzado a continuación evalúa todas las alturas posibles del cuerpo y los elementos html y devuelve el máximo encontrado:

var body = document.body; var html = document.documentElement; var bodyH = Math.max(body.scrollHeight, body.offsetHeight, body.getBoundingClientRect().height, html.clientHeight, html.scrollHeight, html.offsetHeight); // The max height of the body

Un ejemplo de trabajo:

function getHeight() { var body = document.body; var html = document.documentElement; var bodyH = Math.max(body.scrollHeight, body.offsetHeight, body.getBoundingClientRect().height, html.clientHeight, html.scrollHeight, html.offsetHeight); return bodyH; } document.getElementById(''height'').innerText = getHeight();

body,html { height: 3000px; } #posbtm { bottom: 0; position: fixed; background-color: Yellow; }

<div id="posbtm">The max Height of this document is: <span id="height"></span> px</div> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br /> example document body content example document body content example document body content example document body content <br />


Incluso puedes usar esto:

var B = document.body, H = document.documentElement, height if (typeof document.height !== ''undefined'') { height = document.height // For webkit browsers } else { height = Math.max( B.scrollHeight, B.offsetHeight,H.clientHeight, H.scrollHeight, H.offsetHeight ); }

o de una manera más jQuery (ya que como dijiste jQuery no miente) :)

Math.max($(document).height(), $(window).height())


Los tamaños de los documentos son una pesadilla de compatibilidad del navegador porque, aunque todos los navegadores exponen las propiedades de ClientHeight y scrollHeight, no todos están de acuerdo en cómo se calculan los valores.

Solía ​​haber una fórmula compleja de mejores prácticas para evaluar la altura / anchura correcta. Esto implicaba el uso de las propiedades document.documentElement, si estaban disponibles o las propiedades del documento, etc.

La forma más sencilla de obtener la altura correcta es obtener todos los valores de altura que se encuentran en el documento, o documentElement, y usar el más alto. Esto es básicamente lo que hace jQuery:

var body = document.body, html = document.documentElement; var height = Math.max( body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight );

Una prueba rápida con Firebug + jQuery bookmarklet devuelve la altura correcta para ambas páginas citadas, y también lo hace el ejemplo de código.

Tenga en cuenta que probar la altura del documento antes de que esté listo siempre dará como resultado un 0. Además, si carga más cosas o si el usuario cambia el tamaño de la ventana, es posible que deba volver a realizar la prueba. Use onload o un evento preparado para documentos si lo necesita en el momento de la carga, de lo contrario, haga una prueba cada vez que necesite el número.


Mentí, jQuery devuelve el valor correcto para ambas páginas $ (documento) .height (); ... ¿por qué lo dudé?


Obtén el ancho en una forma de navegador / dispositivo cruzado:

function getActualWidth() { var actualWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || document.body.offsetWidh; return actualWidth; }


usar código de soplado para calcular la altura + desplazamiento

var dif = document.documentElement.scrollHeight - document.documentElement.clientHeight; var height = dif + document.documentElement.scrollHeight +"px";


Añadir referencias correctamente

En mi caso, estaba usando una página ASCX y la página aspx que contiene el control ascx no está usando las referencias correctamente. Acabo de pegar el siguiente código y funcionó:

<script src="../js/jquery-1.3.2-vsdoc.js" type="text/javascript"></script> <script src="../js/jquery-1.3.2.js" type="text/javascript"></script> <script src="../js/jquery-1.5.1.js" type="text/javascript"></script>


Cálculo completo de la altura del documento:

Para ser más genérico y encontrar la altura de cualquier documento , simplemente puede encontrar el Nodo DOM más alto en la página actual con una simple recursión:

;(function() { var pageHeight = 0; function findHighestNode(nodesList) { for (var i = nodesList.length - 1; i >= 0; i--) { if (nodesList[i].scrollHeight && nodesList[i].clientHeight) { var elHeight = Math.max(nodesList[i].scrollHeight, nodesList[i].clientHeight); pageHeight = Math.max(elHeight, pageHeight); } if (nodesList[i].childNodes.length) findHighestNode(nodesList[i].childNodes); } } findHighestNode(document.documentElement.childNodes); // The entire page height is found console.log(''Page height is'', pageHeight); })();

Puede probarlo en sus sitios de muestra ( http://fandango.com/ o http://paperbackswap.com/ ) pegando este script en una Consola DevTools.

NOTA: está trabajando con Iframes .

¡Disfrutar!


La respuesta correcta para 2017 es:

document.documentElement.getBoundingClientRect().height

A diferencia de document.body.scrollHeight este método explica los márgenes del cuerpo. También da valor de altura fraccional, que puede ser útil en algunos casos