É bastante conveniente obter o tamanho dos elementos visíveis por JS. Você pode usar este método diretamente:
A cópia do código é a seguinte:
função getDefaultStyle (obj, atributo) {// retorna a função de estilo final, compatível com ie e dom, define parâmetros: objeto de elemento, características de estilo
retornar obj.currentStyle? obj.currentStyle [attribute]: document.defaultView.getComputedStyle (obj, false) [attribute];
}
Mas se esse elemento estiver oculto (exibição: nenhum) e seu tamanho for desconhecido adaptável, o método acima não funcionará! Porque a tela: nenhum elemento não tem tamanho físico! A tragédia aconteceu assim!
Felizmente, também há visibilidade: escondida no CSS, o que é invisível. A maior diferença entre ele e exibição: nenhuma é essa visibilidade: Hidden tem um tamanho físico. Se você tiver tamanhos físicos, poderá obter o tamanho pelo método acima, mas depois de alterar a exibição: nenhum para visibilidade: oculto, haverá um espaço em branco na página. Mesmo se você alterar a visibilidade: oculto para exibir: Nenhum imediatamente após o tamanho, a parte da página ainda será agitada. Então, a melhor maneira é mover esse elemento oculto para fora da tela ou para fora do fluxo de documentos (posição: absoluto). Isso parece perfeito, mas a tragédia acontece novamente. Se você deseja exibir esse elemento novamente, o elemento é invisível e a posição não está correta, porque essa é a visibilidade do elemento: Hidden; Posição: Absoluto. Então, depois de obter o tamanho, você deve restaurar o estilo de volta. É para definir os atributos de posição e visibilidade de volta ao estilo original.
Esta é a implementação básica do JS para obter o tamanho dos elementos ocultos. Se você estiver interessado, pode dar uma olhada no método no livro "Proficiente em JavaScript".
Eu também fiz uma demonstração simples aqui, você pode verificar o código -fonte:
A cópia do código é a seguinte:
<! Doctype html public "-// w3c // dtd xhtml 1.0 transitional // pt" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-bransitional.dtd">
<html xmlns = "http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv = "content-type" content = "text /html; charset = utf-8" />
<title> JS recebe o tamanho do 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>
</head>
<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, O contêiner de teste, o contêiner de teste, o contêiner de teste, o contêiner de teste, o contêiner de teste, o contêiner de teste, o contêiner de teste, o contêiner de teste, o
<div id = "test_display_none" style = "display: nenhum; borda: 10px Solid #cdcdcd"> Este é o contêiner de teste, este é o contêiner de teste, <r /> é o contêiner de teste, <BR />, este é o contêiner, <r />, este é o contêiner de teste, <Br />,
<div id = "test_display_click"> clique em mim </div>
<script type = "text/javascript">
// Juiz Tipo de objeto
função getType (o) {
var _t;
return ((_t = typeof (o)) == "objeto"? O == null && "null" || object.prototype.toString.Call (O) .Slice (8, -1): _ t) .TolowerCase ();
}
// Obtenha estilo de elemento
função getStyle (el, estilenome) {
devolver el.style [StyleName]? El.style [Stylename]: El.CurrentStyle? El.CurrentStyle [StyleName]: Window.GetComputedStyle (el, null) [StyleName];
}
função getstylenum (el, estilenome) {
Return parseint (getStyle (el, stylename) .Place (/px | pt | em/ig, ''));
}
função setStyle (el, obj) {
if (getType (obj) == "objeto") {
para (s em obj) {
var cSsarrrt = s.split ("-");
for (var i = 1; i <cssarrrt.length; i ++) {
cSSarrrt [i] = cSSarrrt [i] .Rearplace (cSSarrrt [i] .Charat (0), cSSarrrt [i] .Charat (0) .toupPercase ());
}
var cSSarrtNew = cSSarrrt.join ("");
el.style [cssarrtNew] = obj [s];
}
}
outro
if (getType (obj) == "string") {
el.style.csStext = obj;
}
}
função getsize (el) {
if (getStyle (el, "display")! = "nenhum") {
Retornar {Width: El.offsetWidth || getstylenum (El, "Largura"), Altura: El.offsetHeight || getstylenum (el, "altura")};
}
var _addcss = {display: "", posição: "absoluto", visibilidade: 'hidden'};
var _oldcss = {};
para (i em _addcss) {
_oldcss [i] = getStyle (el, i);
}
setStyle (el, _addcss);
var _width = el.clientwidth || getStylenum (EL, "Width");
var _Height = el.clientHeight || getstylenum (El, "altura");
para (i em _oldcss) {
setStyle (el, _oldcss);
}
return {width: _width, altura: _height};
}
var dd = document.getElementById ("test_display_block");
alerta (Getsize (dd) .Height);
document.getElementById ("test_display_click"). OnClick = function () {
dd.style.display = "bloco";
document.getElementById ("test_display_none"). style.display = "bloco";
}
alert ($ ("#test_display_none"). Height ());
</script>
</body>
</html>
Off Topic: Geralmente, a estrutura e as bibliotecas JavaScript encapsularam esse método. Por exemplo, JQ, podemos usar diretamente os métodos Hight () e Width () para obter o tamanho dos elementos ocultos.