可以使用文檔對象的getComputedStyle()方法和元素的屬性字段:
var oDiv = document.getElementById("div1");
var css = document.defaultView.getComputedStyle(oDiv, null);
var attr = oDiv.attributes;
這應該爲每個CSS樣式元素有場返回一個對象。然後,您可以編寫一個簡單的,深度優先樹步行到每一個元素遍歷的DOM(我寫這與jQuery,使其易於遵循):
var stack = new Array();
stack.push($('html')[0]);
var i = 0;
while(stack.length > 0 && i < 100){
//pop the next element off the stack
var ele = stack.pop();
var css = document.defaultView.getComputedStyle(ele, null);
var attr = ele.attributes;
//do things with the css object
console.log(css);
//do things with the attributes
console.log(attr);
//add children to the stack
$(ele).children().each(function(index, child){
stack.push(child);
});
i++;
}
注意,我把一個計數器(我),以將迭代次數限制爲100次,並防止在頁面中有大量元素的情況下使瀏覽器崩潰。你可以刪除這個,如果你想,但要小心。還要注意,搜索的根目錄可以是DOM中的任何節點,但我從html標籤開始。
根據您的意見,我將介紹如何執行此操作。請記住,它所做的只是將CSS /屬性對象打印到控制檯,您將需要修改該部分以執行您實際需要的內容。
腳本:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
function doStuff(){
var stack = new Array();
stack.push($('html')[0]);
var i = 0;
while(stack.length > 0 && i < 100){
//pop the next element off the stack
var ele = stack.pop();
var css = document.defaultView.getComputedStyle(ele, null);
var attr = ele.attributes;
//do things with the css object
console.log(css);
//do things with the attributes
console.log(attr);
//add children to the stack
$(ele).children().each(function(index, child){
stack.push(child);
});
i++;
}
}
</script>
HTML按鈕來運行它
<button type="button" onclick="doStuff()">Click Me!</button>
全面實施
<!DOCTYPE html>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
function doStuff(){
var stack = new Array();
stack.push($('html')[0]);
var i = 0;
while(stack.length > 0 && i < 100){
//pop the next element off the stack
var ele = stack.pop();
var css = document.defaultView.getComputedStyle(ele, null);
var attr = ele.attributes;
//do things with the css object
console.log(css);
//do things with the attributes
console.log(attr);
//add children to the stack
$(ele).children().each(function(index, child){
stack.push(child);
});
i++;
}
}
</script>
</head>
<body>
<button type="button" onclick="doStuff()">Click Me!</button>
</body>
</html>
我會有興趣聽到你想用這個完成的事情。這是一個緩慢的操作,通常沒有太多的好處,檢查您在網頁上放置的標籤...
可能重複的[我如何獲得jQuery的所有元素css屬性的列表?](http:///stackoverflow.com/questions/1471118/how-can-i-get-list-of-all-element-css-attributes-with-jquery) – Josh
@Josh:這個問題有100多個問題,但我正在尋找「插件」而不是實際的代碼。 Noob in Javascript/jQuery,我就是。 – Jawad
@Jawad:有一個鏈接到[this](http://stackoverflow.com/a/6416477/420001)。 – Josh