如何使用 jQuery 将 div 的宽度设置为百分比?
Using the width function:
$('div#somediv').width('70%');
will turn:
<div id="somediv" />
into:
<div id="somediv" style="width: 70%;"/>
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 + '%');
Here is an alternative that worked for me:
$('div#somediv').css({'width': '70%'});