[英]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.