问题
i have this code:
HTML
<div class="bar-value"></div>
CSS
.bar-value{
width: 50%;
height: 28px;
background: #8BBDE8;
}
JQUERY
$(document).ready(function(){
var percent = $('.bar-value').css('width');
});
the problem is that this returns the width of the div in pixels (in this case: 200px). I want that to return the value of the div in percentage (50%).
Thanks in advance!
回答1:
To get a percentage, you need the width of it's parent. Try this :
$(document).ready(function(){
var element = $('.bar-value');
var percent = element.css('width')/element.parent().width()*100+'%';
});
回答2:
This question has already been answered here
You have to implement it yourself :
var width = $('.bar-value').css('width');
var parentWidth = $('.bar-value').offsetParent().css('width');
var percent = 100*width/parentWidth;
来源:https://stackoverflow.com/questions/23462600/get-css-width-of-an-element-and-convert-it-to-percentage