javascript jquery - 获取尚未应用的类的 CSS 属性值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10958869/
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
jquery -Get CSS properties values for a not yet applied class
提问by Jaideep Singh
i have a same questionasked here(wasnt able to comment on it,maybe dont have a priviledge) , i want to get css width value defined in stylesheet but not yet applied on any element in dom ,(its bootstrap css with grid with responsive media queries)
我在这里问了一个同样的问题(无法对其发表评论,也许没有特权),我想获得样式表中定义的 css 宽度值,但尚未应用于 dom 中的任何元素,(它的引导 css 与网格具有响应媒体查询)
.span6 {
width: 570px;
}
However solution provided in above referenced question return 0 i.e like this
然而,上面引用的问题中提供的解决方案返回 0,即像这样
$('<div/>').addClass('span6').width();
but works if i do something like this
但如果我做这样的事情
$('<div/>').addClass('span6').hide().appendTo('body').width();
any easy way without appending that div?
没有附加那个div的任何简单方法?
回答by Jose Rui Santos
In order to read a CSS property value from a nonexistent element, you need to dynamically insert that element (as hidden) to the DOM, read the property and finally remove it:
为了从不存在的元素中读取 CSS 属性值,您需要将该元素(作为隐藏)动态插入 DOM,读取该属性并最终将其删除:
var getCSS = function (prop, fromClass) {
var $inspector = $("<div>").css('display', 'none').addClass(fromClass);
$("body").append($inspector); // add to DOM, in order to read the CSS property
try {
return $inspector.css(prop);
} finally {
$inspector.remove(); // and remove from DOM
}
};
回答by Biff MaGriff
Great answer by Jose. I modified it to help with more complex css selectors.
何塞的回答很好。我修改了它以帮助处理更复杂的 css 选择器。
var getCSS2 = function (prop, fromClass, $sibling) {
var $inspector = $("<div>").css('display', 'none').addClass(fromClass);
if($sibling != null){
$sibling.after($inspector); //append after sibling in order to have exact
} else {
$("body").append($inspector); // add to DOM, in order to read the CSS property
}
try {
return $inspector.css(prop);
} finally {
$inspector.remove(); // and remove from DOM
}
};