我今天一直在測試Javascript CSS函數,並注意到當使用.style.cssText時,它只給我使用JS設置的CSS。如何獲取元素的所有CSS
我反而想要得到所有CSS的元素,所以我猜測我做錯了什麼或者可能需要另一個函數,而不是像getComputedStyle,但對於整個CSS而不是單個屬性值,但我找不到我的東西搜索時需要。
所以我的問題是怎樣才能從我的代碼,如最後部分完整的CSS:
background-color: #ffcccc; font-family:"Helvetica Neue", Arial, "Lucida Grande", sans-serif; font-size: 13px; color: #ff0000;
而不是當前的短CSS是輸出?
<html>
<head>
<style type="text/css" media="screen">
.MyDiv001 {
background-color: #ffcccc;
font-family:"Helvetica Neue", Arial, "Lucida Grande", sans-serif;
}
.MyDiv002 {
background-color: #ccffcc;
font-family:"Helvetica Neue", Helvetica, Arial, sans-serif;
}
</style>
</head>
<body>
<div id="MyDiv001" class="MyDiv001">This is MyDiv001</div>
<div id="MyDiv002" class="MyDiv002">This is MyDiv002</div>
<br /><hr><br />
<script type="text/javascript">
// Select the MyDiv001 element
var MyDiv001 = document.getElementById("MyDiv001"); // Select MyDiv001
// Set some style property values for MyDiv001
MyDiv001.style.setProperty("font-size", "13px", null);
MyDiv001.style.setProperty("color", "#ff0000", null);
// Get the Computed Style for MyDiv001
var MyDiv001Style = window.getComputedStyle(MyDiv001);
// Show the MyDiv001 style property values
document.write("MyDiv001 background-color = " + MyDiv001Style.getPropertyValue("background-color") + "<br />");
document.write("MyDiv001 font-family = " + MyDiv001Style.getPropertyValue("font-family") + "<br />");
document.write("MyDiv001 font-size = " + MyDiv001Style.getPropertyValue("font-size") + "<br /><br />");
// Select the MyDiv002 element
var MyDiv002 = document.getElementById("MyDiv002"); // Select MyDiv002
// Set some style property values for MyDiv002
MyDiv002.style.setProperty("font-size", "16px", null);
MyDiv002.style.setProperty("color", "#0000ff", null);
// Get the Computed Style for MyDiv002
var MyDiv002Style = window.getComputedStyle(MyDiv002);
// Show the MyDiv002 style property values
document.write("MyDiv002 background-color = " + MyDiv002Style.getPropertyValue("background-color") + "<br />");
document.write("MyDiv002 font-family = " + MyDiv002Style.getPropertyValue("font-family") + "<br />");
document.write("MyDiv002 font-size = " + MyDiv002Style.getPropertyValue("font-size") + "<br /><br />");
// Not what i was expecting
document.write("MyDiv001 CSS = " + MyDiv001.style.cssText+ "<br />"); // How do i get the full css?
document.write("MyDiv002 CSS = " + MyDiv002.style.cssText+ "<br />"); // How do i get the full css?
</script>
</body>
</html>
編輯 - 我想使用規則的Javascript如果可能的話,希望一個固定的我的代碼版本,爲什麼不返回完整的CSS,由於原因的答案。
的可能重複[jQuery的可以得到一個元素相關聯的所有CSS樣式?](http://stackoverflow.com/questions/754607/can-jquery-get-all-css-styles-associated-with - 元素) – 2013-02-21 10:44:18
不,這不是,這是使用jQuery,而我有上述代碼中的常規JS。我也想知道我做錯了什麼,所以我知道爲什麼它沒有返回所有CSS元素。 – zeddex 2013-02-21 10:53:40
找到一篇文章http://www.quirksmode.org/dom/getstyles.html - 我不是js的專家,但看起來很直接 – ggdx 2013-02-21 13:47:23