tamaño div dinamico dinamicamente create crear contenido con cambiar altura ajustar javascript html css

dinamico - create element div javascript



Estableciendo la altura de un DIV dinámicamente (8)

En una aplicación web, tengo una página que contiene un DIV que tiene un ancho automático según el ancho de la ventana del navegador.

Necesito una altura automática para el objeto. El DIV comienza aproximadamente 300 px desde la pantalla superior, y su altura debe hacer que se extienda hasta la parte inferior de la pantalla del navegador. Tengo una altura máxima para el contenedor DIV, por lo que tendría que haber una altura mínima para el div. Creo que puedo limitar eso en CSS y usar Javascript para manejar el cambio de tamaño del DIV.

Mi javascript no es tan bueno como debería ser. ¿Hay algún script fácil de escribir que pueda hacer esto por mí?

Editar: El DIV alberga un control que hace su propio manejo de desbordamiento (implementa su propia barra de desplazamiento).


El DIV alberga un control que hace su propio manejo de desbordamiento.


Pruebe esta función simple y específica:

function resizeElementHeight(element) { var height = 0; var body = window.document.body; if (window.innerHeight) { height = window.innerHeight; } else if (body.parentElement.clientHeight) { height = body.parentElement.clientHeight; } else if (body && body.clientHeight) { height = body.clientHeight; } element.style.height = ((height - element.offsetTop) + "px"); }

No depende de la distancia actual desde la parte superior del cuerpo que se especifica (en caso de que cambie 300px).

EDITAR: por cierto, desearía llamar esto a cada vez que el usuario cambiara el tamaño del navegador, por lo que necesitaría conectar el controlador de eventos para eso, por supuesto.


Si entiendo lo que estás preguntando, este debería ser el truco:

// the more standards compliant browsers (mozilla/netscape/opera/IE7) use // window.innerWidth and window.innerHeight var windowHeight; if (typeof window.innerWidth != ''undefined'') { windowHeight = window.innerHeight; } // IE6 in standards compliant mode (i.e. with a valid doctype as the first // line in the document) else if (typeof document.documentElement != ''undefined'' && typeof document.documentElement.clientWidth != ''undefined'' && document.documentElement.clientWidth != 0) { windowHeight = document.documentElement.clientHeight; } // older versions of IE else { windowHeight = document.getElementsByTagName(''body'')[0].clientHeight; } document.getElementById("yourDiv").height = windowHeight - 300 + "px";


Con correcciones menores:

function rearrange() { var windowHeight; if (typeof window.innerWidth != ''undefined'') { windowHeight = window.innerHeight; } // IE6 in standards compliant mode (i.e. with a valid doctype as the first // line in the document) else if (typeof document.documentElement != ''undefined'' && typeof document.documentElement.clientWidth != ''undefined'' && document.documentElement.clientWidth != 0) { windowHeight = document.documentElement.clientHeight; } // older versions of IE else { windowHeight = document.getElementsByTagName(''body'')[0].clientHeight; } document.getElementById("foobar").style.height = (windowHeight - document.getElementById("foobar").offsetTop - 6)+ "px"; }


Lo más simple que podría venir ...

function resizeResizeableHeight() { $(''.resizableHeight'').each( function() { $(this).outerHeight( $(this).parent().height() - ( $(this).offset().top - ( $(this).parent().offset().top + parseInt( $(this).parent().css(''padding-top'') ) ) ) ) }); }

Ahora todo lo que tiene que hacer es agregar la clase resizableHeight a todo lo que quiera autoestar (a su padre).


¿Qué debería pasar en caso de desbordamiento? Si desea que solo llegue al final de la ventana, use posicionamiento absoluto:

div { position: absolute; top: 300px; bottom: 0px; left: 30px; right: 30px; }

Esto colocará el DIV 30px desde cada lado, 300px desde la parte superior de la pantalla, y al ras con la parte inferior. Agregar un overflow:auto; para manejar casos donde el contenido es más grande que el div.

Editar: @El que marcó esto, una explicación sería agradable ... ¿Hay algún problema con la respuesta?

document.getElementById(''myDiv'').style.height = 500;

Este es el código JS muy básico requerido para ajustar la altura de su objeto dinámicamente. Acabo de hacer esto mismo donde tenía una propiedad de altura automática, pero cuando añadí algo de contenido a través de XMLHttpRequest , necesité cambiar el tamaño de mi div principal y esta propiedad de compensación de valor funcionó en IE6 / 7 y FF3.


inspirado en @ jason-bunting, lo mismo para la altura o el ancho:

function resizeElementDimension(element, doHeight) { dim = (doHeight ? ''Height'' : ''Width'') ref = (doHeight ? ''Top'' : ''Left'') var x = 0; var body = window.document.body; if(window[''inner'' + dim]) x = window[''inner'' + dim] else if (body.parentElement[''client'' + dim]) x = body.parentElement[''client'' + dim] else if (body && body[''client'' + dim]) x = body[''client'' + dim] element.style[dim.toLowerCase()] = ((x - element[''offset'' + ref]) + "px"); }