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

如何使用javascript for loop按类名获取元素宽度?,javascript,jquery,html,css,Javascript,Jquery,Html,Css,当我测试时,它将是警报空白值和30px 我想得到警报400px和30px我该怎么办 .div\u封面\u螺纹\u图像{ 宽度:400px; } 测验 测验 var div_cover_threads_image_Elem=document.getElementsByClassName'div_cover_threads_image'; forvar i=0,len=div\u cover\u threads\u image\u Elem.length;i正如您标记jQuery一样,即使没有明确

当我测试时,它将是警报空白值和30px 我想得到警报400px和30px我该怎么办

.div\u封面\u螺纹\u图像{ 宽度:400px; } 测验 测验 var div_cover_threads_image_Elem=document.getElementsByClassName'div_cover_threads_image';
forvar i=0,len=div\u cover\u threads\u image\u Elem.length;i正如您标记jQuery一样,即使没有明确定义宽度,这也将返回元素宽度:

.div\u封面\u螺纹\u图像{ 宽度:400px; } 测验 测验 var div_cover_threads_image_Elem=document.getElementsByClassName'div_cover_threads_image'; forvar i=0,len=div\u cover\u threads\u image\u Elem.length;i您在第二个div中使用了Element.style,这意味着内联样式。对于第一个,您需要使用window.getComputedStyleElement,[,pseudoElt]来获取它的所有样式

通过以下方式提取宽度:

var width=window.getComputedStyle(Element,null).getPropertyValue('width');
返回的值大约为400px。如果希望使用不带单位的数值,请尝试parseFloat

如果使用jQuery,事情会变得更简单。只需$'.div\u cover\u threads\u image'.width

来自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>

可能的重复您已经通过标记jQuery而在代码片段中使用普通javascript造成了一些混乱。你想要哪个?
.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>