Convert pixel to percentage using javascript

一世执手 提交于 2019-12-19 12:05:35

问题


I have a table header's width in pixel. on click of a function i need to convert pixel to 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>

回答1:


percentage is a relative value.

with one value like 100px you cannot make a percentage.

you need to have relative value like screenWidth (for suppose) 1366px so that you will get percentage of that value.

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



回答2:


//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;
}


来源:https://stackoverflow.com/questions/15807021/convert-pixel-to-percentage-using-javascript

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