以CSS中定义的单位获取元素的宽度

时间:2014-07-04 10:03:04

标签: javascript jquery css width

让我说我有:

.item {
    width: 33%;
}

问题是如果使用jQuery我必须检索宽度:

$('.item').first().css('width')

返回实际宽度(以像素为单位)

如何获得%?我是否必须根据实际父母的宽度进行计算?

1 个答案:

答案 0 :(得分:1)

你必须做计算

  

100 *(元素宽度/父元素宽度)

var el = $('.item').first(),
    width = (100 * parseFloat(el.css('width')) / parseFloat(el.parent().css('width'))) + '%';

var el = $('.item').first(),
    width = (100 * parseFloat(el.width()) / parseFloat(el.parent().width())) + '%';