get css width of an element and convert it to percentage

妖精的绣舞 提交于 2021-02-11 17:26:17

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!