[英]Get Each and Every CSS Property and HTML Attribute for a Given Element
使用Javascript / jQuery,可以獲取文檔中給定Element的屬性名稱及其值以及HTML屬性名稱及其值。 不管它們是否是:
內聯樣式
<h1 style="font-weight="900">Heading 1</h1>
嵌入式的
<style>
h1
{
font-weight: bold;
}
</style>
已連結
<link href="main.css" rel="stylesheet" type="text/css" media="all" />
進口的
@import url("reset.css");
而無論
嗯,可以啟動FF中的Firebug或Developer Tools,以及其他UA中的類似工具,但是它們缺乏一些功能。 我正在尋找一種jQuery插件類型,其中該元素顯示在左側,而以上所有元素顯示在右側(也許在iframe中?)。
我只是制作了一個文檔(一個非常簡單的文檔,可能只包含一個元素),然后將其顯示在瀏覽器的左側,而將其顯示在右側。
您可以使用文檔對象的getComputedStyle()方法和元素的attribute字段:
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++;
}
請注意,我在其中放置了一個計數器(i),以將迭代次數限制為100,如果頁面中有大量元素,則可以避免瀏覽器崩潰。 您可以根據需要刪除此文件,但要小心。 還要注意,搜索的根可以是DOM中的任何節點,但我是從html標記開始的。
根據您的評論,我將逐步介紹您如何實現此目的。 請記住,它所做的只是將CSS / attribute對象打印到控制台,您將需要修改該部分以執行您實際想要的操作。
腳本:
<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>
我很想聽聽您要完成的工作。 這是一個緩慢的操作,通常檢查一下放置在頁面上的標簽並沒有太大好處。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.