2010-02-25 57 views
1

沒有人知道如何獲取所有樣式應用於使用jquery的id(所以我可以稍後在另一個標籤中重用)?像 CSS:jquery從ID獲取樣式

div#myid{ 
width:100px; 
height:100px;} 

,所以我以後可以這樣做:

for (var parts in $('#myid').css()) 
alert ('all parts of the style' + parts); 

回答

2

$( '#身份識別碼')ATTR( '類')返回的類的字符串。

你應該可以從這裏弄清楚。

var classes = $('#myid').attr('class').split(' '); 
for(var c in classes) 
{ 
    alert(classes[c]); 
} 
+0

一個小的變化將警報(三); //類[c]會拋出錯誤 – Raja 2010-02-25 18:53:09

+0

不知道'c'由於某種原因返回爲int ... – ctrlShiftBryan 2010-02-25 19:16:56

0

這不是jQuery的,但效果很好:

var style = window.getComputedStyle(document.getElementById('myid'), null); 
    alert(style.color); 

您可以通過$('#myid').get(0)代替document.getElementById('myid')如果你真的想在這裏jQuery的使用。

這適用於由CSS給出的樣式或直接應用於具有style屬性的元素。

0

不確定..我曾嘗試過attr('class'),它返回空。現在嘗試再次產生相同的結果(差不多)。我想在jQuery中的attr('class')與通過id定義的樣式完全相同。嘗試運行這個,讓我知道如果你得到不同的結果請:

<html> 
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.2.min.js"></script> 
<script type="text/javascript"> 
    $(document).ready(function(){ 
    alert($('#myid').attr('class')); // returns 'empty' 
    var classes = $('#myid').attr('class').split(' '); 
    for(var c in classes){ 
     alert(c); // returns 0 
    } 
    }); 
</script> 

<style> 
#myid { 
width:100px; 
height:100px; 
background:red; 
} 
</style> 

<body> 
<div id="myid"></div> 
</body> 

</html> 
+0

是window.getComputedStyle跨瀏覽器兼容的任何機會嗎? :) – joe 2010-02-25 22:29:53