使用javascript将像素转换为百分比

时间:2013-04-04 09:13:26

标签: javascript function width pixel percentage

我有一个表格标题的宽度(以像素为单位)。点击一个函数我需要将像素转换为百分比。

<th field="Column1" id="Column1" noresize="true" width="100px">
    <label id="Column1" onclick="getCustomGridColName(this.id,'inner__fghgh');" style="cursor:pointer; font-family: Times; font-size:12pt;">
        Column1
    </label>
</th>

2 个答案:

答案 0 :(得分:9)

百分比是相对值。

有一个像100px这样的值,你无法创造一个百分比。

你需要有像screenWidth(假设)1366px这样的相对值,这样你才能获得该值的百分比。

var pixels = 100;
var screenWidth = window.screen.width;
var percentage = ( screenWidth - pixels ) / screenWidth ; // 0.92%

答案 1 :(得分:0)

//Transform pixel in percentage
/* - totalpx: Total of pixels depending on the width or height, could be 1920.0 or 1080.0, 1280.0 or 720.0, etc...
     respectively.
   - px: the pixel desidered to be converted.
   - ItIsHeight: boolean to know if is axis x or y ot make the correct calculation.
   - BaseOfConversionWidth & BaseOfConversionHeight: the base of conversion from the original pixel are take it, if
     the design is HD ready then will be 1280.0 and 720.0, if is full HD then will be 1920.0 and 1080.0, etc... */
public Double TransformPercentage(Double Totalpx, Double px, boolean ItIsHeight, double BaseOfConversionWidth, double BaseOfConversionHeight) {
    if (ItIsHeight)
        return (px / BaseOfConversionHeight) * Totalpx;
    else
        return (px / BaseOfConversionWidth) * Totalpx;
}