javascript - 你如何找到 "display: none"元素的维度?

标签 javascript html css

我在 div 中有一些子元素,它们应用了 CSS display: none,我想找出子元素的尺寸是多少。我该怎么做?

Fiddle Demo

var o = document.getElementById('output');
var wmd1 = document.getElementById('whats-my-dims1');
var wmd2 = document.getElementById('whats-my-dims2');
o.innerHTML = 'wmd1: "' + wmd1.clientWidth + '", "' + wmd1.clientHeight + '", wmd2: "' + wmd2.clientWidth + '", "' + wmd2.clientHeight + '"';
#some-hidden-div{
  display: none;
}
.whats-my-dims{
  width: 69px;
  height: 42px;
  background-color: #f00;
}
<div id='output'>Processing... :p</div>
<div id='some-hidden-div'>
  <div class='whats-my-dims' id='whats-my-dims1'></div>
</div>
<div class='whats-my-dims' id='whats-my-dims2'></div>

我只能使用纯 JavaScript(不能使用 jQuery)。

我无法更改顶部/左侧/右侧/底部/变换/翻译/等,因为这将成为可以包含子元素的动画 Sprite 表自定义组件的一部分。

最佳答案

使用window.getComputedStyle()

var o = document.getElementById('output');
var wmd1 = document.getElementById('whats-my-dims1');
var wmd2 = document.getElementById('whats-my-dims2');
o.innerHTML = 'wmd1: "' + window.getComputedStyle(wmd1).getPropertyValue("width") 
+ '", "' 
+ window.getComputedStyle(wmd1).getPropertyValue("height") 
+ '", wmd2: "' 
+ window.getComputedStyle(wmd2).getPropertyValue("width") + '", "' 
+ window.getComputedStyle(wmd2).getPropertyValue("height") + '"';
#some-hidden-div{
  display: none;
}
.whats-my-dims{
  display:block;
  width: 69px;
  height: 42px;
  background-color: #f00;
}
<div id='output'>
  Processing... :p
</div>
<div>
  Sooo... How do I get the width and height of whats-my-dims1?
</div>
<div id='some-hidden-div'>
  <div class='whats-my-dims' id='whats-my-dims1'></div>
</div>
<div class='whats-my-dims' id='whats-my-dims2'></div>

jsfiddle https://jsfiddle.net/h9b17vyk/3/

关于javascript - 你如何找到 "display: none"元素的维度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35519137/

相关文章:

javascript - jQuery全屏部分向左滑动,向右滑动

php - 显示用户详细信息而不保存上一个 session

html - partial 内部的指令在顶部出现一个栏

html - CSS IE6 案例 - 内部 div 不适合 100%

jquery - 如何解决 IE7 中复杂的 Z-index 问题

javascript - 使用 .find() 取消选中复选框

javascript - 运行功能然后点击链接

javascript - 未定义 Chrome 扩展脚本/函数(Bootstrap Native?)

javascript - 在 Controller 中传递 html 字符串并放入 .html (Angular js)

css - 内联 svg 图标呈现乱码