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

使用javascript将像素转换为百分比,javascript,function,width,pixel,percentage,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;

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

<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>

专栏1

百分比是一个相对值

使用一个值,如
100px
,则无法计算百分比

您需要有相对值,如screenWidth(假设)
1366px
,以便获得该值的百分比

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

百分比是多少?桌子?页面?确切的百分比是多少。相对于屏幕,最接近的父元素,另一个元素,它本身不是另一个元素的百分比。。相同的元素本身。。100px=?%使用scriptI我认为您需要阅读,它需要是某个百分比,在CSS中具有绝对或相对定位,通常是最接近的父级。
//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;
}