在jQuery中将px中的.width()转换为%,以获得Bootstrap的附加标签

我目前有:

jQuery的

$(document).ready(function () { $('.span-fix').each(function(){ /* Do this for each extended input */ var wide = $(this).width(), /* create a variable that holds the width of the form */ label = $(this).prev('.add-on').width(); /* create another variable that holds the width of the previous label */ $(this).width( wide - label ); /* subtract the label width from the input width and apply it in px */ }); }); 

HTML

 
Location

显示问题的小提琴: http : //jsfiddle.net/SuguM/

但是,这会在px应用新的宽度,而我使用的是流畅的布局,需要再次使用百分比。

有没有办法将px转换为%

实际上,您省略了计算中的填充。 我认为这段代码可以帮到你。

编辑:

这是firefox的代码:

 $(document).ready(function () { $('.span-fix').each(function(){ /* Do this for each extended input */ var label = $(this).prev('.add-on').outerWidth(); /* create another variable that holds the width of the previous label */ $(this).width( (1-(label + $(this).outerWidth() - $(this).width())/$(this).parent().width()) *100 + "%" ); }); }); 

这是chrome的代码:

 $(document).ready(function () { $('.span-fix').each(function(){ /* Do this for each extended input */ var label = $(this).prev('.add-on').outerWidth(); /* create another variable that holds the width of the previous label */ $(this).css("width", (1-(label)/$(this).parent().width()) *100 + "%" ); }); });​ 

对于chrome,如果在检查width css属性时使用width方法,则必须设置属性css,属性值不等于计算的值。

这里有一个关于jsFiddle的例子。

这里有两个实现的jsFiddle。 现在您只需要检测浏览器。

这取父母的宽度,只计算百分比。

 $(this).width((wide - label)/$(this).parent().width()*100+'%'); 

基于我之前的post 。

 var getPercent = function(elem) { var elemName = elem.attr("id"), width = elem.width(), parentWidth = elem.offsetParent().width(), percent = Math.round(100 * width / parentWidth); return percent; }; 

这将计算整个文档的百分比:

 $(this).width((wide - label) * 100 / $(document).width()+'%');