kumarjcet
¿Por qué obtengo Element offsetHeight “0”? incluso la altura original del elemento no se muestra
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
/* Added for Menu */
.navbar
{
list-style: none;`enter code here`
padding: 0 10px;
margin: 0;
float: left;
width: 980px;
background: url(images/navbar.gif) repeat-x;
}
.navbar ul
{
list-style: none;
padding: 0px;
margin: 0;
float: left;
width: 260px;
}
.navbar ul li
{
float:left;
position:relative;
z-index:1000;
margin:0px;
padding:0px;
}
.navbar ul li ul
{
display:none;
border:none;
width: 260px;
padding:0 0px 0px 0px;
}
.navbar ul li a
{
font-size: 12px;
float:left;
display:block;
line-height:3.1em;
padding:0 16px 0 16px;
text-decoration:none;
color:#FFF;
}
.navbar ul li:hover
{
width:auto;
}
.navbar ul li:hover a
{
background:url(images/navbar_subnav.png) repeat-x scroll 0 0 transparent; text-decoration:none;
}
.navbar ul li:hover ul
{
display:block;
position:absolute;
z-index:998;
top:0px;
margin-top:25px;
left:0;
}
.navbar ul li:hover ul li ul
{
background-position: center bottombottom;
cursor: pointer;
}
.navbar ul li:hover ul li a
{
display:block;
line-height:1.3em;
padding:4px 16px 4px 16px;
border-bottom:1px solid #205284;
border-left:1px solid #205284;
border-right:1px solid #205284;
border-top:1px solid #205284;
z-index: 10000;
width:200px;
}
.navbar ul li:hover ul li a:hover
{
background-color:#000;
text-decoration:underline;
color: #0099FF;
cursor: hand;
}
.navbar ul li a:hover ul
{
display:block;
position:absolute;
z-index: 998;
top:3.1em;
t\op:3.0em;
left:0;
marg\in-top:0.1em;
}
.navbar ul li a:hover ul li a
{
display:block;
height:1px;
line-height:1.3em;
padding:4px 16px 4px 16px;
background-color:#000;
font-weight:normal;
color:#FFF;
}
.navbar ul li a:hover ul li a ul
{
visibility:hidden;
height:0px;
width:0px;
position:absolute;
z-index: 997;
}
.navbar ul li a:hover ul li a:hover
{
background-color:#000;
text-decoration:underline;
}
</style>
</head>
<body>
<div class="navbar">
<ul>
<li>
<a href="#">menu item 1</a>
<ul style="top:0px" >
<li style="width:288px;"><center><a href="#" onmouseover="movedown()" onmouseout="stopscroll()"><img src="images/menu-arrow-down.png" width="8" height="6" alt="Down"></a></center></li>
<script> //<![CDATA[
var speed=2
iens6=document.all||document.getElementById
ns4=document.layers
if (iens6){
document.write('<div id="container" style="position:relative;width:310px;height:165px;overflow:hidden;border:0px solid #205284">')
document.write('<div id="content" style="position:absolute;width:290px;left:0px;top:-1px;">')
}
//]]></script>
<ilayer name="nscontainer" width="190">
<layer name="nscontent" width="290" height="155" visibility="hidden">
<li style="top:-1px;"><a href="#">sub menu item 1 menu item 1</a></li>
<li style="top:-1px;"><a href="#">sub menu item 2 menu item 1</a></li> <li style="top:-1px;"><a href="#">sub menu item 3</a></li>
<li style="top:-1px;"><a href="#">sub menu item 1</a></li>
<li style="top:-1px;"><a href="#">sub menu item 1</a></li>
<li style="top:-1px;"><a href="#">sub menu item 2</a></li>
<li style="top:-1px;"><a href="#">sub menu item 3</a></li>
<li style="top:-1px;"><a href="#">sub menu item 1</a></li>
<li style="top:-1px;"><a href="#">sub menu </a></li>
<li style="top:-1px;"><a href="#">sub menu </a></li>
<li style="top:-1px;"><a href="#">sub menu </a></li>
<li style="top:-1px;"><a href="#">sub menu </a></li>
<li style="top:-1px;"><a href="#">sub menu </a></li>
<li style="top:-1px;"><a href="#">sub menu</a></li>
</layer>
</ilayer>
<script> //<![CDATA[
if (iens6)
{
document.write('</div></div>')
var crossobj=document.getElementById? document.getElementById('content') : document.all.content
//alert("document.getElementById('content').offsetHeight :"+ document.getElementById('content').offsetHeight);
alert("crossobj.prototype.outerHeight" + crossobj.prototype.outerHeight);
var contentheight=crossobj.offsetHeight
//var contentheight=document.getElementById('content').style.height;
//alert("ContentHeight :"+contentheight);
}
else if (ns4)
{
var crossobj=document.nscontainer.document.nscontent
var contentheight=crossobj.clip.height
}
function movedown(){
if (window.moveupvar) clearTimeout(moveupvar)
{
if (iens6&&parseInt(crossobj.style.top)>=(contentheight*(-1)+100))
{
crossobj.style.top=parseInt(crossobj.style.top)-speed+"px"
}
else if(ns4&&crossobj.top>=(contentheight*(-1)+100))
{
crossobj.top-=speed
}
/*else
{
crossobj.style.top=parseInt(crossobj.style.top)-speed+"px"
}*/
}
movedownvar=setTimeout("movedown()",20)
}
function moveup()
{
if (window.movedownvar) clearTimeout(movedownvar)
{
if (iens6&&parseInt(crossobj.style.top)<=0)
{
crossobj.style.top=parseInt(crossobj.style.top)+speed+"px"
}
else if (ns4&&crossobj.top<=0)
{
crossobj.top+=speed
}
moveupvar=setTimeout("moveup()",20)
}
}
function getcontent_height()
{
if (iens6)
{
//alert("getcontent_height : "+document.getElementById("content").style.height);
//contentheight=document.getElementById("content").style.height;
contentheight=crossobj.offsetHeight
}
else if (ns4)
{
document.nscontainer.document.nscontent.visibility="show"
}
}
window.onload=getcontent_height;
//]]></script>
<li><center><a href="#" onmouseover="moveup()" onmouseout="stopscroll()"><img src="images/menu-arrow-down.png" width="8" height="6" alt="Down"></a> </center></li>
</ul>
</li>
</ul>
</div>
</body>
</html>
A veces, offsetHeight devolverá cero porque el elemento que ha creado aún no se ha representado en el Dom. Escribí esta función para tales circunstancias:
function getHeight(element)
{
element.style.visibility = "hidden";
document.body.appendChild(element);
var height = element.offsetHeight + 0;
document.body.removeChild(element);
element.style.visibility = "visible";
return height;
}
-
Tuve un problema con el elemento que desaparecía de su lugar original. agregando
element = element.cloneNode(true);
a la parte superior de la función lo arregló.– Samal Rasmussen
9 de mayo de 2017 a las 10:29
-
¿Qué haces cuando esto le está pasando al cuerpo?
– merhoo
31 de marzo de 2020 a las 1:37
-
@merhoo No usarías la función anterior. Estas diciendo eso
document.body.offsetHeight
es igual a “0”? ¿Se realiza esta medición antes o después de la evento de carga? ¿Ya se han renderizado todos los contenidos del cuerpo añadidos dinámicamente (si los hay)? ¿El contenido del cuerpo contiene únicamente elementos absolutamente posicionados?– Lonnie Mejor
1 de abril de 2020 a las 6:55
estas tratando de conseguir offsetHeight
de un elemento oculto. el CSS .navbar ul li ul
tiene display:none
eso haría que todo su contenido fuera invisible, incluido crossobj
y no puede obtener la altura de los elementos que no se muestran, su altura simplemente se pone 0
.
-
hola, gracias por tu respuesta… basado en ese único menú sobre su submenú de visualización si elimino eso significa que por defecto muestra el menú y el submenú… ¿puedes ayudarme a prevenir esto…
– kumarjcet
4 de agosto de 2011 a las 9:50
-
hay un truco para este problema que puede colocar su etiqueta alrededor de -1000px -1000px en lugar de usar
display:none
y luego usaroffsetHeight
para medir la altura, y en lugar de cambiar la visualización, deberá cambiar la posición para que la etiqueta sea visible– Infinito Kamyar
4 de agosto de 2011 a las 10:07
HazeyAce
ACTUALIZAR
Los cambios aplicados a los elementos DOM no se aplican de inmediato, todos los cambios realizados en el DOM en un solo ciclo de ejecución se recopilan y aplican en un repintado.
Por lo tanto, debe esperar a que se complete el repintado antes de intentar leer las dimensiones actualizadas del elemento.
requestAnimationFrame es un método que se ejecuta antes de cada repintado.
requestAnimationFrame(() => {
element = document.getElementById("your_ID");
let height = element.offsetHeight;
console.log("debug height: " + height);
});
Shaun R Stewart
Otro “truco” es establecer momentáneamente la visibilidad de los objetos en hidden
, su pantalla para bloquear. Y luego obtener el offsetHeight
. Luego simplemente invierta eso configurando la pantalla en none
y visibilidad a visible
. Por supuesto, esto solo funcionará si no interrumpe el flujo del diseño de la página (es decir, todo cambia en la página como si hubiera algo allí, pero no se muestra nada en el espacio). Pero si es algo que está indexado en z o flotante o quizás en una posición absoluta, debería funcionar bien.
Hay una forma más fácil de hacerlo. Tenía muchos iframes con diferentes ID y nombres, así que esto es lo que hice. Agregué el botón en la ventana principal, que al hacer clic hace esto
var iWin = document.querySelector(your iframe id here).contentWindow;
iWin.postMessage("button is clicked","*");
//you can send the id of the required frame as the message
Ponga esto dentro de la secuencia de comandos de la ventana secundaria.
window.onload = function(){
window.addEventListener('message',(e)=>{
if(e.data == "showcomment"){
//I am just sending the height and iframe name cause I have many iframes
//with different names
window.parent.postMessage({winHeight:document.body.offsetHeight,winName:
window.name},"*");
}
});
}
Ahora, el último paso, pon esto en el script de la ventana principal.
window.addEventListener('message',(e)=>{
//here I am getting element with that name and setting its height you can change it
document.getElementsByName(`${e.data.winName}`)[0].height = e.data.winHeight + 10;
//I added 10 as extra height , you can ignore it
})