如何使用javascript for循环按类名获取元素宽度?

时间:2017-11-07 02:26:38

标签: javascript jquery html css

当我测试时,它会提醒blank value30px 我想提醒400px30px我该怎么办?

.div_cover_threads_image{
  width: 400px;
}
<div class="div_cover_threads_image">
test
</div>

<div class="div_cover_threads_image" style="width: 30px;">
test
</div>


<script>     
var div_cover_threads_image_Elem = document.getElementsByClassName('div_cover_threads_image');
for(var i=0, len=div_cover_threads_image_Elem.length; i<len; i++)
{
  	alert(div_cover_threads_image_Elem[i].style.width);
}  
</script>

3 个答案:

答案 0 :(得分:2)

当您标记了jQuery时,即使没有明确定义宽度,也会返回元素宽度:

&#13;
&#13;
.div_cover_threads_image{
  width: 400px;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="div_cover_threads_image">
test
</div>

<div class="div_cover_threads_image" style="width: 30px;">
test
</div>


<script>     
var div_cover_threads_image_Elem = document.getElementsByClassName('div_cover_threads_image');
for(var i=0, len=div_cover_threads_image_Elem.length; i<len; i++)
{
  	alert($(div_cover_threads_image_Elem[i]).width());
}  
</script>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您在第二个div上使用了window.getComputedStyle(Element,[, pseudoElt]),这意味着内联样式。对于第一个,您需要使用var width=window.getComputedStyle(Element,null).getPropertyValue('width'); 来获取它的所有样式。

通过以下方式提取宽度:

400px

返回的值类似于parseFloat。如果您希望使用不带单位的数值,请尝试var els = document.getElementsByClassName( 'div_cover_threads_image' ); for(var i=0, len=els.length; i<len; i++) { var computed = getComputedStyle( els[i], null ); alert( computed.getPropertyValue( 'width' ) ); }

$('.div_cover_threads_image').width();

如果你使用jQuery,事情就会变得更简单。只需{{1}}

答案 2 :(得分:0)

来自jquery,

.div_cover_threads_image{
  width: 400px;
}

<div class="div_cover_threads_image">
test
</div>

<div class="div_cover_threads_image" style="width: 30px;">
test
</div>


<script>     
$( ".div_cover_threads_image" ).each(function() {
  alert($( this ).width());
});
</script>