在 jQuery 中获取 CSS 规则的百分比值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/744319/
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 CSS rule's percentage value in jQuery
提问by montrealist
Let's say the rule is as follows:
假设规则如下:
.largeField {
width: 65%;
}
Is there a way to get '65%' back somehow, and not the pixel value?
有没有办法以某种方式恢复“65%”,而不是像素值?
Thanks.
谢谢。
EDIT:Unfortunately using DOM methods is unreliable in my case, as I have a stylesheet which imports other stylesheets, and as a result the cssRulesparameter ends up with either nullor undefinedvalue.
编辑:不幸的是,在我的情况下使用 DOM 方法是不可靠的,因为我有一个导入其他样式表的样式表,因此cssRules参数以null或undefined值结束。
This approach, however, would work in most straightforward cases (one stylesheet, multiple separate stylesheet declarations inside the headtag of the document).
但是,这种方法适用于大多数简单的情况(一个样式表,文档的head标记内的多个单独的样式表声明)。
采纳答案by Adam Lassek
There's no built-in way, I'm afraid. You can do something like this:
恐怕没有内置的方法。你可以这样做:
var width = ( 100 * parseFloat($('.largeField').css('width')) / parseFloat($('.largeField').parent().css('width')) ) + '%';
回答by redexp
Most easy way
最简单的方法
$('.largeField')[0].style.width
// >>> "65%"
回答by timofey.com
This is most definitely possible!
这绝对是可能的!
You must first hide() the parent element. This will prevent JavaScript from calculating pixels for the child element.
您必须首先 hide() 父元素。这将阻止 JavaScript 计算子元素的像素。
$('.parent').hide();
var width = $('.child').width();
$('.parent').show();
alert(width);
See my example.
看我的例子。
Now... I wonder if I'm first to discover this hack:)
现在......我想知道我是否是第一个发现这个黑客的人:)
Update:
更新:
One-liner
单线
element.clone().appendTo('body').wrap('<div style="display: none"></div>').css('width');
It will leave behind a hidden element before the </body>
tag, which you may want to .remove()
.
它会在</body>
标签之前留下一个隐藏元素,你可能想要.remove()
。
See an example of one-liner.
I'm open to better ideas!
我愿意接受更好的想法!
回答by Gumbo
You could access the document.styleSheets
object:
您可以访问该document.styleSheets
对象:
<style type="text/css">
.largeField {
width: 65%;
}
</style>
<script type="text/javascript">
var rules = document.styleSheets[0].rules || document.styleSheets[0].cssRules;
for (var i=0; i < rules.length; i++) {
var rule = rules[i];
if (rule.selectorText.toLowerCase() == ".largefield") {
alert(rule.style.getPropertyValue("width"));
}
}
</script>
回答by ddanone
Late, but for newer users, try this if the css style contains a percentage:
晚了,但对于新用户,如果 css 样式包含百分比,请尝试此操作:
$element.prop('style')['width'];
回答by Leonard Pauli
A jQuery plugin based on Adams answer:
一个基于 Adams 的 jQuery 插件回答:
(function ($) {
$.fn.getWidthInPercent = function () {
var width = parseFloat($(this).css('width'))/parseFloat($(this).parent().css('width'));
return Math.round(100*width)+'%';
};
})(jQuery);
$('body').html($('.largeField').getWidthInPercent());?????
Will return '65%'. Only returns rounded numbers to work better if you do like if (width=='65%'). If you would have used Adams answer directly, that hadn't worked (I got something like 64.93288590604027). :)
将返回“65%”。如果您喜欢 if (width=='65%'),则只返回四舍五入的数字以更好地工作。如果您直接使用 Adams 回答,那没有用(我得到了类似 64.93288590604027 的信息)。:)
回答by Gregory Magarshak
Building on timofey's excellent and surprising solution, here is a pure Javascript implementation:
基于 timofey 出色且令人惊讶的解决方案,这是一个纯 Javascript 实现:
function cssDimensions(element)
var cn = element.cloneNode();
var div = document.createElement('div');
div.appendChild(cn);
div.style.display = 'none';
document.body.appendChild(div);
var cs = window.getComputedStyle
? getComputedStyle(cn, null)
: cn.currentStyle;
var ret = { width: cs.width, height: cs.height };
document.body.removeChild(div);
return ret;
}
Hope it's helpful to someone.
希望它对某人有帮助。
回答by Horst Walter
I have a similar issue in Getting values of global stylesheet in jQuery, eventually I came up with the same solution as above.
我在Get values of global stylesheet in jQuery 中有一个类似的问题,最终我想出了与上面相同的解决方案。
Just wanted to crosslink the two questions so others can benefit from later findings.
只是想将这两个问题交联起来,以便其他人可以从以后的发现中受益。
回答by B T
There's nothing in jQuery, and nothing straightforward even in javascript. Taking timofey's answer and running with it, I created this function that works to get any properties you want:
jQuery 中没有任何东西,甚至在 javascript 中也没有任何简单的东西。接受 timofey 的回答并运行它,我创建了这个函数来获取你想要的任何属性:
// gets the style property as rendered via any means (style sheets, inline, etc) but does *not* compute values
// domNode - the node to get properties for
// properties - Can be a single property to fetch or an array of properties to fetch
function getFinalStyle(domNode, properties) {
if(!(properties instanceof Array)) properties = [properties]
var parent = domNode.parentNode
if(parent) {
var originalDisplay = parent.style.display
parent.style.display = 'none'
}
var computedStyles = getComputedStyle(domNode)
var result = {}
properties.forEach(function(prop) {
result[prop] = computedStyles[prop]
})
if(parent) {
parent.style.display = originalDisplay
}
return result
}
回答by Zachary Horton
Convert from pixels to percentage using cross multiplication.
使用交叉乘法从像素转换为百分比。
Formula Setup:
公式设置:
1.) (element_width_pixels/parent_width_pixels) = (element_width_percentage / 100)
1.) (element_width_pixels/parent_width_pixels) = (element_width_percentage / 100)
2.) element_width_percentage = (100 * element_width_pixels) / parent_width_pixels
2.) element_width_percentage = (100 * element_width_pixels) / parent_width_pixels
The actual code:
实际代码:
<script>
var $width_percentage = (100 * $("#child").width()) / $("#parent").width();
</script>