如何使用jQuery获得与一个元素相关的所有CSS样式
在这篇文章中,我们将了解如何使用jQuery获取与元素相关的应用CSS属性,并将通过实例了解其实现。给定一个包含一些CSS属性的HTML文档,我们需要使用jQuery来获取某个特定元素的所有CSS样式。这两种方法如下。
方法1:在这种方法中,我们将使用document.defaultView.getComputedStyle()方法来获取与该特定元素相关的所有层叠样式。之后,通过遍历对象,将样式逐一追加到一个字符串中。
详情请参考HTML DOM defaultView属性和getComputedStyle()方法。
例子:这个例子实现了document.defaultView.getComputedStyle()方法来检索与特定元素相关的各种应用风格属性。
<!DOCTYPE HTML>
<html>
<head>
<title>
Getting all the CSS styles
of an element using jQuery
</title>
</head>
<body style="text-align:center;">
<h1>GeeksforGeeks</h1>
<p id="GFG_UP"></p>
<button onclick="GFG_Fun();"> Click Here </button>
<p id="GFG_DOWN"></p>
<script>
var up = document.getElementById('GFG_UP');
var down = document.getElementById('GFG_DOWN');
up.innerHTML = "Click on the button "
+ "to get the all CSS styles "
+ "associated with the element.";
function GFG_Fun() {
var ar = document.defaultView.getComputedStyle(up, null);
var str = "";
for(var key in ar) {
str = str + key + ': ' + ar[key] + "-";
}
down.innerHTML = str;
}
</script>
</body>
</html>
输出:
方法2:在这种方法中,只有特定的样式被提取出来。我们可以传递样式的名称。方法cssSpecific被定义为在传递的字符串上进行字符串操作,从对象中获取属性,并以字符串形式返回。
例子:这个例子的实现是为了只检索与一个元素相关的特定造型属性。
<!DOCTYPE HTML>
<html>
<head>
<title>
Getting all the CSS styles
of an element using jQuery
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js">
</script>
</head>
<body style="text-align:center;">
<h1>GeeksforGeeks</h1>
<p id="GFG_UP"></p>
<button onclick="GFG_Fun();"> Click Here </button>
<p id="GFG_DOWN"></p>
<script>
var up = document.getElementById('GFG_UP');
var down = document.getElementById('GFG_DOWN');
up.innerHTML = "Click on the button to get"
+ " only specific CSS styles associated "
+ "with the element.";
(function() {
.fn.cssSpecific = function(str) {
var ob = {};
if(this.length) {
var css = str.split(', ');
var prms = [];
for(var i = 0, ii = css.length; i < ii; i++) {
prms = css[i].split(':');
ob[.trim(prms[0])] =(this).css(.trim(prms[1] || prms[0]));
}
}
return ob;
};
})(jQuery);
function GFG_Fun() {
var styles =('#GFG_UP').cssSpecific(
'color, backgroundColor, opacity, height, lineHeight:height');
down.innerHTML = JSON.stringify(styles);
}
</script>
</body>
</html>
输出: