2017-11-07 7 views
1

私はそれが警告されますblank value30px 私は警告を取得したい400px30pxどうすればいいですか?javascript forループを使用してclassnameで要素の幅を取得するにはどうすればよいですか?

.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++) 
 
{ 
 
    \t alert(div_cover_threads_image_Elem[i].style.width); 
 
} 
 
</script>

+0

可能性のある重複した[あなたはどのようにJavaScriptでCSSルール値を読みますか](https://stackoverflow.com/questions/324486/how-do-you-read -css-rule-values-with-javascript) –

+0

あなたは 'jQuery'にタグをつけてあなたのスニペットにバニラ' javascript'を使っていくつかの混乱を作りました。どちらがいいですか? –

答えて

2

あなたはjQueryのをタグ付けしましたように、これは何の幅が明示的に定義されていない場合でも、幅の要素を返します。

.div_cover_threads_image{ 
 
    width: 400px; 
 
}
<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++) 
 
{ 
 
    \t alert($(div_cover_threads_image_Elem[i]).width()); 
 
} 
 
</script>

0

あなたはElement.styleを使用2番目のdivはインラインスティを意味しますル。最初のスタイルの場合は、すべてのスタイルを取得するためにwindow.getComputedStyle(Element,[, pseudoElt])を使用する必要があります。返される値は400pxようになります

var width=window.getComputedStyle(Element,null).getPropertyValue('width'); 

はで幅を抽出します。単位なしの数値を使用する場合は、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')); 
} 

jQueryを使用すると、操作が簡単になります。ただ、$('.div_cover_threads_image').width(); jqueryのから

0

、の

.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> 
関連する問題