如何在JavaScript中将px转换为vw?

Kap*_*pys 17 javascript css jquery html5 css3

我想转换pxvw在JavaScript中,我该怎么办呢?

我一直在寻找它,但我没有找到任何东西.

所以,

1px→?VW

谢谢.

fca*_*ran 37

1px =(100vw/[document.documentElement.clientWidth] px)

例如 - 如果您的视口很500px宽(等于定义100vw),那么

1px =(100vw/500px)= 0.2vw

我曾经.clientWidth排除任何滚动条的计算

  • 为什么排除滚动条?我观察到 100vw **包括滚动条**(如果出现)。所以 `window.innerWidth` 已经为我提供了 px 和 vw 之间的准确转换。但 document.documentElement.clientWidth 还没有。尝试过 Windows Chrome 和 Firefox、Mac Chrome 和 Safari。 (2认同)

小智 16

公式是这样的

大众 px:

100 * px / 窗口宽度

vh 中的 px:

100 * 像素/窗口高度

vh(像素):

窗口高度 * vh / 100

大众汽车(像素):

windowWidth * vw / 100

一些灵感代码:(虽然我是一个 JS 菜鸟)

function viewport_convert(px = 0, vw = 0, vh = 0){
    if(px != 0){
        if(vw){
            return (100 * px / window.innerWidth);
        } else {
            return (100 * px / window.innerHeight);
        }
    } else if(vw != 0 && vh != 0){
        var w_h_arr = [];
        w_h_arr["width"] = Math.ceil((window.innerWidth * vw / 100));
        w_h_arr["height"] = Math.ceil((window.innerHeight * vh / 100));
        return w_h_arr;
    } else if(vw != 0){
        return Math.ceil((window.innerWidth * vw / 100));
    } else if(vh != 0){
        return Math.ceil((window.innerHeight * vh / 100));
    }
}
Run Code Online (Sandbox Code Playgroud)