如何从内联样式中获得以百分比而非像素为单位的高度

How to get height in percentage instead of in pixels from inline style?

本文关键字:百分比 像素 为单位 高度 样式      更新时间:2023-09-26

因此,基本上,我有许多元素的内联样式为height和百分比。虽然,当我试图将高度保存为要使用的变量时,它将其保存为像素。

例如:

<div class="wrapper">
    <div style="height:10%;">Testing 123</div>
    <div style="height:20%;">Testing 123</div>
    <div style="height:30%;">Testing 123</div>
</div>
$('.wrapper > div').each(function () {
    var height = $(this).css('height');
    console.log(height);  
});

上述代码将打印到控制台40px80px120px。我需要这些值作为百分比。有没有办法做到这一点,或者我应该将这些值保存在数据属性中以供使用?

工作演示

您可以使用:

$('.wrapper > div').each(function () {
    var height = this.style.height;
    console.log(height); 
});

更新的Fiddle

正如Felix所说,您可以使用$(this)[0],但下面的代码也可以使用

$('.wrapper > div').each(function () {
    var height = this.style.height;
    alert(height); 
});

演示:-

http://jsfiddle.net/b427X/1/