2017-07-21 8 views
-1

私はこのようなdom要素を持っています。Javascriptでhtmlスタイルのプロパティを取得する方法

<div class="MyClass" id="123" style="width: 228px; overflow: auto; height: 100px;"> 
    <div class="loading-indicator">loading...</div> 
</div> 

私は後で使用することができ、いくつかの変数に228と店舗でタグdivから幅を取りたいです。ここで

var st = 228px; // dynamically

私が使用していました。

var secondDiv = document.createElement('div'); 
secondDiv.style = "background-color:#2C8DC2;color:white;padding:5px; margin-top:102px;height: 50px; width : st; border-style: solid;"; 

今、私はここにしようとしています何がある:

するvar ABC = firstDiv.getAttribute( 'スタイル'); "width: 228px; overflow: auto; height: 100px;"

abc.width;

をしかし、これは未定義来ている:

私は取得しています。

この値を取得する方法。

+0

[*スタイル*プロパティが(https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style)オブジェクトではなく文字列であります。 – RobG

+0

@RobG正確には、文字列として来ています。 – David

+0

はい、 'string'となっています。それが彼らの設計方法です。 –

答えて

-1

なぜ使用しないでしょうかjQuery

console.log($(`#123`).css('width'));
<script 
 
    src="https://code.jquery.com/jquery-3.2.1.js" 
 
    integrity="sha256-DZAnKJ/6XZ9si04Hgrsxu/8s717jcIzLy3oi35EouyE=" 
 
    crossorigin="anonymous"></script> 
 
    
 
<div class="MyClass" id="123" style="width: 228px; overflow: auto; height: 100px;"> 
 
    <div class="loading-indicator">loading...</div> 
 
</div>

0

あなたはこのように試みることができます。それでもまっすぐJavaScriptでそれを実現したい場合は

window.getComputedStyle(ele); gives you element style. 

var ele = document.getElementById("123"), // Do not use # 
 
    eleStyle = window.getComputedStyle(ele); 
 
/* Below is the width of ele */ 
 
var eleWidth = eleStyle.width; 
 
console.log(eleWidth);
<div class="MyClass" id="123" style="width: 228px; overflow: auto; height: 100px;"> 
 
    <div class="loading-indicator">loading...</div> 
 
</div>

0

jQueryでは、

alert($("#123").css("width")); // which will return 228px;

<div class="MyClass" id="123" style="width: 228px; overflow: auto; height: 100px;"> 
    <div class="loading-indicator">loading...</div> 
</div> 

行うことができます

使用この参照:How to get an HTML element's style values in javascript?

関連する問題