使用 jQuery 将宽度设置为百分比
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2124351/
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
提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:49:10 来源:igfitidea点击:
Setting width as a percentage using jQuery
提问by Prasad
How can I set the width of a div as a percentage using jQuery?
如何使用 jQuery 将 div 的宽度设置为百分比?
回答by Darin Dimitrov
回答by Jonathan Elder
Hemnath
赫姆纳特
If your variable is the percentage:
如果您的变量是百分比:
var myWidth = 70;
$('div#somediv').width(myWidth + '%');
If your variable is in pixels, and you want the percentage it take up of the parent:
如果您的变量以像素为单位,并且您想要它占父级的百分比:
var myWidth = 140;
var myPercentage = (myWidth / $('div#somediv').parent().width()) * 100;
$('div#somediv').width(myPercentage + '%');
回答by joaorodr84
Here is an alternative that worked for me:
这是一个对我有用的替代方法:
$('div#somediv').css({'width': '70%'});