jQuery 如何使用jQuery以百分比获取div的宽度?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18785951/
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
How to get width of a div in percentage using jQuery?
提问by sun
I have a div, and I'd like to know if there's a way to get its width in percentage using jQuery.
我有一个 div,我想知道是否有办法使用 jQuery 获得其宽度的百分比。
Here's my code:
这是我的代码:
$(document).ready(function(){
var f = $('.f').width();
alert(f);
});
I tried to use %
as an argument like this width(%)
, but this is setting the width as %
not getting the value in a percentage format. Can someone tell me what should I do to get in percentage instead?
我试图%
用作这样的参数width(%)
,但这是将宽度设置为%
未以百分比格式获取值。有人可以告诉我我该怎么做才能获得百分比?
Any help is profusely appreciated.
非常感谢任何帮助。
回答by Reinstate Monica Cellio
To use your example code...
要使用您的示例代码...
$(document).ready(function(){
var f = $(".f").width() / $('.f').parent().width() * 100;
alert(f);
});
回答by Johan
If you want the width relative to the body:
如果你想要相对于身体的宽度:
var percent = $('.f').width() / $('body').width() * 100;
console.log(Math.round(percent).toFixed(2));
Is this what you're asking for?
这是你要的吗?
回答by Ganesh Pandhere
you will need to get viewport width and then calculate your element width percentage in accordance with viewport width.
您需要获取视口宽度,然后根据视口宽度计算元素宽度百分比。
var width = $('#someElt').width();
var parentWidth = $('#someElt').offsetParent().width(); // this will return parent element's width which also can be replaced with docuent to get viewport width
var percent = 100*width/parentWidth;
回答by zkanoca
$(document).ready(function(){
var f = $('.f').width();
var pw = $('.f').parent().width();
var rate = (f/pw*100) + '%';
$('.f').html( rate);
});
it is parent item's with. So if you rate the .f div's width to parent item's width you get that value.
它是父项的。因此,如果您将 .f div 的宽度评定为父项的宽度,您将获得该值。