在JS中将vh单位转换为px

zzz*_*Bov 7 javascript css viewport-units

不幸的100vh是,并不总是与100%浏览器高度相同,如下例所示.

html,
body {
    height: 100%;
}

body {
    overflow: scroll;
}

.vh {
    background-color: blue;
    float: left;
    height: 50vh;
    width: 100px;
}

.pc {
    background-color: green;
    float: left;
    height: 50%;
    width: 100px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="vh"></div>
<div class="pc"></div>
Run Code Online (Sandbox Code Playgroud)

这个问题在iPhone 6+上更为明显,上部位置栏和下部导航栏如何在滚动时展开和收缩,但不包括在计算中100vh.

100%可以通过window.innerHeight在JS中使用来获取高度的实际值.

有没有一种方便的方法来计算100vhJS中像素的当前转换?

我试图避免需要生成带内联样式的虚拟元素来计算100vh.

出于此问题的目的,假设一个恶意环境,其中max-widthmax-height可能产生不正确的值,并且100vh页面上没有任何现有元素.基本上,假设任何可能出错的东西都有本机浏览器功能,但保证是干净的.

到目前为止我提出的最好的是:

function vh() {
    var div,
        h;
    div = document.createElement('div');
    div.style.height = '100vh';
    div.style.maxHeight = 'none';
    div.style.boxSizing = 'content-box';
    document.body.appendChild(div);
    h = div.clientHeight;
    document.body.removeChild(div);
    return h;
}
Run Code Online (Sandbox Code Playgroud)

但是对于计算当前值来说似乎太冗长了100vh,我不确定它是否还有其他问题.

Pab*_*noz 4

怎么样:

function viewportToPixels(value) {
  var parts = value.match(/([0-9\.]+)(vh|vw)/)
  var q = Number(parts[1])
  var side = window[['innerHeight', 'innerWidth'][['vh', 'vw'].indexOf(parts[2])]]
  return side * (q/100)
}
Run Code Online (Sandbox Code Playgroud)

用法:

viewportToPixels('100vh') // window.innerHeight
viewportToPixels('50vw') // window.innerWidth / 2
Run Code Online (Sandbox Code Playgroud)

  • 错误,iOS 上的 `innerHeight` 不是 `100vh` http://output.jsbin.com/diwoyevive/quiet (2认同)