使用 jQuery 获取*所有* CSS 属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3965310/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get *all* CSS attributes with jQuery
提问by Kyle
Here's how you get one css attribute using jQuery:
以下是使用 jQuery 获取一个 css 属性的方法:
$('someObject').css('attribute')
$('someObject').css('attribute')
How do you get them all? (without specifying and preferably in the following format so it can be reapplied with jQuery later):
你如何得到它们?(不指定,最好采用以下格式,以便以后可以用 jQuery 重新应用):
cssObj = {
'overflow':'hidden',
'height':'100%',
'position':'absolute',
}
Thanks!!
谢谢!!
EDIT
编辑
The methods I'm trying to get are declared in a style sheet (they are not inline). Sorry for not specifying.
我试图获取的方法在样式表中声明(它们不是内联的)。抱歉没有指定。
采纳答案by Andrew M
What about something like this:
像这样的事情怎么样:
jQuery CSS plugin that returns computed style of element to pseudo clone that element?
jQuery CSS 插件返回元素的计算样式以伪克隆该元素?
It is ugly, but it appeared to work for the poster...
它很丑,但它似乎适用于海报......
This also may be of interest: https://developer.mozilla.org/en/DOM:window.getComputedStyle
这也可能很有趣:https: //developer.mozilla.org/en/DOM: window.getComputedStyle
回答by svk
See this live exampleusing the jQuery attribute selector
使用 jQuery 属性选择器查看此实时示例
$(document).ready(function() {
alert($("#stylediv").attr('style'));
});?
回答by pyrospade
Not sure how cross-browser this one is, but it works in Chrome -
不确定这个是如何跨浏览器的,但它在 Chrome 中工作 -
https://gist.github.com/carymrobbins/223de0b98504ac9bd654
https://gist.github.com/carymrobbins/223de0b98504ac9bd654
var getCss = function(el) {
var style = window.getComputedStyle(el);
return Object.keys(style).reduce(function(acc, k) {
var name = style[k],
value = style.getPropertyValue(name);
if (value !== null) {
acc[name] = value;
}
return acc;
}, {});
};
回答by Surender Lohia
window.getComputedStyle(element);
window.getComputedStyle(元素);
// For example
var element = document.getElementById('header');
window.getComputedStyle(element);