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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15807021/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 02:10:09  来源:igfitidea点击:

Convert pixel to percentage using javascript

javascriptfunctionwidthpixelpercentage

提问by Rachel

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>

回答by Sandeep

percentage is a relative value.

百分比是一个相对值。

with one value like 100pxyou cannot make a percentage.

一个值就像100px你不能做一个百分比。

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

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

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

回答by Dan

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