Es bastante conveniente obtener el tamaño de los elementos visibles por JS. Puede usar este método directamente:
La copia del código es la siguiente:
función getDefaultStyle (obj, atributo) {// Devuelve la función de estilo final, compatible con IE y DOM, establece parámetros: objeto de elemento, características de estilo
return obj.CurrentStyle? obj.CurrentStyle [atributo]: document.defaultView.getComputedStyle (obj, falso) [atributo];
}
Pero si este elemento está oculto (pantalla: ninguno) y su tamaño es desconocido adaptable, ¡entonces el método anterior no funcionará! Porque la pantalla: ¡Ninguno de los elementos no tiene tamaño físico! ¡La tragedia sucedió así!
Afortunadamente, también hay visibilidad: oculto en CSS, que es invisible. La mayor diferencia entre TI y pantalla: ninguna es esa visibilidad: Hidden tiene un tamaño físico. Si tiene tamaños físicos, puede obtener el tamaño por el método anterior, pero después de cambiar la pantalla: Ninguno a Visibilidad: Oculto, habrá un espacio en blanco en la página. Incluso si cambia de visibilidad: oculto para mostrar: ninguno inmediatamente después de obtener el tamaño, la parte de la página aún se sacudirá. Entonces, la mejor manera es mover este elemento oculto fuera de la pantalla o fuera de la secuencia de documentos (posición: absoluta). Esto parece perfecto, pero la tragedia vuelve a ocurrir. Si desea mostrar este elemento nuevamente, el elemento es invisible y la posición no es correcta, porque esta es la visibilidad del elemento: Oculta; posición: absoluta. Entonces, después de obtener el tamaño, debe restaurar el estilo. Es para establecer los atributos de posición y visibilidad al estilo original.
Esta es la implementación básica de JS para obtener el tamaño de los elementos ocultos. Si está interesado, puede echar un vistazo al método en el libro "Competente en JavaScript".
También he hecho una demostración simple aquí, puede verificar el código fuente:
La copia del código es la siguiente:
<! DocType html public "-// w3c // dtd xhtml 1.0 Transitional // en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transicional.dtd ">
<html xmlns = "http://www.w3.org/1999/xhtml">
<Evista>
<meta http-equiv = "content-type" content = "text /html; charset = utf-8" />
<title> JS obtiene el tamaño del elemento oculto </title>
<style type = "text/css">
</style>
<script type = "text/javascript" src = "http://www.css88.com/tool/css3preview/jquery-1.4.2.min.js"> </script>
</ablo>
<Body>
<div id="test_display_block" style="display:none; border:10px solid #CDCDCD; margin-left: 100px">This is the test container, the visible container<br />This is the test container, the visible container<br />This is the test container, the visible container<br />This is the test container, the visible container<br />This is the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, the test container, el contenedor de prueba, el contenedor de prueba, el contenedor de prueba, el contenedor de prueba, el contenedor de prueba, el contenedor de prueba, el contenedor de prueba, el contenedor de prueba, el
<div id = "test_display_none" style = "visualización: ninguno; border: 10px sólido #cdcdcd"> Este es el contenedor de prueba, este es el contenedor de prueba, <Br />> Este es el contenedor de prueba, <Br /> Este es el contenedor de prueba, <Br /> Este es el Tester, <Br /> Este es el contenedor de Test, <Br /> </enviv.
<div id = "test_display_click"> Haga clic en mí </div>
<script type = "text/javaScript">
// juzga el tipo de objeto
función getType (o) {
var _t;
return ((_t = typeof (o)) == "objeto"? O == null && "null" || object.prototype.ToString.call (o) .slice (8, -1): _ t) .tolowercase ();
}
// Obtener estilo de elemento
function getStyle (el, stylename) {
regresar el.style [stylename]? El.style [stylename]: el.currentstyle? El.CurrentStyle [stylename]: window.getComputedStyle (el, null) [stylename];
}
función getStylenum (el, stylename) {
return parseint (getStyle (el, stylename) .replace (/px | pt | em/ig, ''));
}
funciones setstyle (el, obj) {
if (getType (obj) == "objeto") {
para (s en obj) {
var cssarrrt = s.split ("-");
para (var i = 1; i <cssarrrt.length; i ++) {
cssarrrt [i] = cssarrrt [i] .replace (cssarrrt [i] .charat (0), cssarrrt [i] .charat (0) .touppercase ());
}
var cssarrtnew = cssarrrt.Join ("");
El.style [cssarrtnew] = obj [s];
}
}
demás
if (getType (obj) == "cadena") {
el.style.csstext = obj;
}
}
función getSize (el) {
if (getStyle (El, "Display")! = "Ninguno") {
return {ancho: el.offsetwidth || getStylenum (el, "ancho"), altura: el.Offsetheight || getStylenum (el, "altura")};
}
var _addcss = {display: "", posición: "absoluto", visibilidad: 'oculto'};
var _oldcss = {};
para (i en _addcss) {
_oldcss [i] = getStyle (el, i);
}
setStyle (el, _addcss);
var _width = el.clientwidth || getStylenum (el, "ancho");
var _Height = el.clientHeight || getStylenum (el, "altura");
para (i en _oldcss) {
setStyle (el, _oldcss);
}
return {ancho: _width, altura: _Height};
}
var dd = document.getElementById ("test_display_block");
alerta (getize (dd) .Height);
document.getElementById ("test_display_click"). onClick = function () {
dd.style.display = "bloque";
document.getElementById ("test_display_none"). style.display = "bloque";
}
alert ($ ("#test_display_none"). Height ());
</script>
</body>
</html>
Tema fuera: Generalmente, el marco y las bibliotecas de JavaScript han encapsulado este método. Por ejemplo, JQ, podemos usar directamente los métodos de altura () y ancho () para obtener el tamaño de los elementos ocultos.