jQuery宽度返回像素而不是%

dom*_*ino 1 jquery jquery-ui

 <div class="ui-progress" style="width: 10%;">

 console.log($(this).width());
Run Code Online (Sandbox Code Playgroud)

以像素为单位返回宽度而非%.我如何获得百分比?

the*_*dox 7

试试这个:

var width = $('.ui-progress').width();
var parentWidth = $('.ui-progress').offsetParent().width();
var percent = 100*width/parentWidth;
Run Code Online (Sandbox Code Playgroud)

要么

var width = ( 100 * parseFloat($('.ui-progress').css('width')) / parseFloat($('.ui-progress').parent().css('width')) ) + '%';
Run Code Online (Sandbox Code Playgroud)

注意

您可以使用.offsetParent(),如果母公司.ui-progress有CSS position:absolute.