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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28295072/
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-08-23 01:33:58  来源:igfitidea点击:

How can I convert px to vw in JavaScript?

javascriptjqueryhtmlcss

提问by Kappys

I want to convert pxto vwin JavaScript, how can I do it?

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

I've been looking for it, but I haven't found anything.

我一直在寻找它,但我什么也没找到。

So,

所以,

1px → ? vw

1px → ? 大众

Thanks.

谢谢。

回答by Fabrizio Calderan

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

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

e.g. — If your viewport was 500pxwide (equals by definition to 100vw) then

例如——如果你的视口很500px宽(根据定义等于100vw)那么

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

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

I used .clientWidthto exclude any scrollbarfrom computation

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

回答by enguerranws

As 1vw / 1vh represents 1/100th of the viewport width / height, you could achieve this using something like :

由于 1vw / 1vh 代表视口宽度/高度的 1/100,您可以使用以下方法实现:

var newWidth = yourElement.outerwidth / document.documentElement.clientWidth *100;
yourElement.style.width = newWidth +'vw';

I thought about use a Math.round() to get clean number, but you'll surely get wrong dimensions if you exclude decimals.

我想过使用 Math.round() 来获得干净的数字,但是如果排除小数,您肯定会得到错误的尺寸。

Can't you change this values directly in CSS (e.g. with another stylesheet) ? It seems really dirty to convert it via Javascript.

您不能直接在 CSS 中更改此值(例如,使用另一个样式表)吗?通过 Javascript 转换它似乎很脏。

Also, according to Errand's comment, if you simply convert your px to vw/vh, it won't make your current HTML/CSS magically fit in the screen.

此外,根据 Errand 的评论,如果您只是将 px 转换为 vw/vh,它不会使您当前的 HTML/CSS 神奇地适合屏幕。