当样式为auto或100%时,如何获取元素的高度?

9

当元素的样式为"width:100%; height:auto;"时,如何获得该元素的确切像素高度或宽度?

我不能将其嵌套在div中并通过这种方式获取高度/宽度!

我猜想javascript可以在这里提供帮助。

编辑:我正在使用以下内容:

var collectNodes = document.getElementById('fade').children;

collectNodes[y].height() // ??

以下代码会输出字符串 "auto":
```html

以下代码提供了字符串 "auto":

```
collectNodes[0].style.height;

编辑2:这是我的代码。

<div id="divId">
    <img class="node" src="somePic0.png" style="z-index:10; opacity:0;"/>
    <img class="node" src="somePic1.png" style="z-index:9; opacity:0;"/>
    <img class="node" src="somePic2.png" style="z-index:8; opacity:1;"/> 
    <img class="node" src="somePic3.png" style="z-index:7; opacity:1;"/>
    <img class="node" src="somePic4.png" style="z-index:6; opacity:1;"/>
</div>

<script>
    var collectNodes = document.getElementById('divId').children; 
    var y = 0;
    for ( var x = 0; x < collectNodes.length; x++ ) {
        if ( collectNodes[x].style.opacity !== "" && !y ) {
            y = x;
        }
    }

    alert(collectNodes[y].height); // This alerts the string "auto" and not pixel height
</script>

你是在使用jQuery或其他库,还是应该使用纯JavaScript? - Jaco Koster
任何一种都可以 :) 我更喜欢jQuery,但JavaScript也同样适用! - basickarl
1个回答

12
你可以使用纯JavaScript实现此操作,如下所示:

JavaScript

var divHeight;
var obj = document.getElementById('id_element');

if(obj.offsetHeight) {
    divHeight=obj.offsetHeight;

} else if(obj.style.pixelHeight) {
    divHeight=obj.style.pixelHeight;

}

有了jQuery库,做以下技术更容易了:

JQuery

var height = $('#element').height();

编辑

现在可以在容器内使用许多元素:

HTML

<div id="divId">
    <img class="node" src="path/to/pic" style="z-index:10; opacity:0;"/>
    <img class="node" src="path/to/pic" style="z-index:9; opacity:0;"/>
    <img class="node" src="path/to/pic" style="z-index:8; opacity:1;"/> 
    <img class="node" src="path/to/pic" style="z-index:7; opacity:1;"/>
    <img class="node" src="path/to/pic" style="z-index:6; opacity:1;"/>
</div>

为了兼容性,我将你的透明度更改为可见性。不要使用display:none;否则高度分析会失败 ;).

JQuery

$("#divId img").each(function(index, picture) {
   var height = $(picture).height();
   //Do everything you want with the height from the image now
});

可以查看示例来查看它的工作方式。


更新了我的问题并发布了一些JavaScript! - basickarl
使用jQuery,您可以使用each来解析容器中的每个元素,能否提供一些HTML代码以便更好地帮助您? - soyuka
工作得很好,只是由于我使用的插件需要它具有不透明度:( 我有"collectNodes[y]",因为它循环遍历所有图像并选择我希望从中获取高度的图像!但是代码"collectNodes[y].height"只返回"auto"! - basickarl
1
我的代码也适用于不透明度,我正在编辑 ;) 你的图片使用什么条件?class、id、data属性? - soyuka
我想通了:$("#fade img").each(function(index, picture) { if ($(picture).css("opacity") == 1 && done==0) { done=1; imageHeight = $(picture).height(); imageWidth = $(picture).width(); }
}); - 谢谢 :D
- basickarl

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接