Javascript以像素为单位获得100vh

Cur*_*tis 10 javascript css

<html>
    <head>
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
    </head>
    <body>
        <div style='height:4000px;background:#EEE;'>
            <div id=vh style='height:100vh;background:#AFB'>
                100vh
                <br>
                <br>
                <br>
                <button onclick='show()' style='font-size:55px'>
                    Show
                </button>
            </div>
            more stuff
        </div>
        <script>
            var vh=document.getElementById('vh')
            function show()
            {
                alert('window.innerHeight='+window.innerHeight
                +', window.outerHeight='+window.outerHeight
                +', screen.height='+screen.height
                +', document.documentElement.clientHeight='+document.documentElement.clientHeight
                +', vh.clientHeight='+vh.clientHeight)
            }
        </script>
    </body>
</html>
Run Code Online (Sandbox Code Playgroud)

http://curtastic.com/testvh.html

在我的iPad上,100vh div大小为1256像素.(如果你最近的卷轴是向上的)

window.innerHeight是1217.

screen.height是1024.

window.outerHeight为0.

documentElement.clientHeight是4016.

有没有什么方法在javascript中得到这个号码1256?除了制作div并将其设置为高度:100vh然后检查其clientHeight?

我的字体大小也设置为10vh.那个像素究竟是什么?

我没有使用jQuery.

我知道100vh比移动设备上的可见视口更高,因此浏览器栏可以改变大小而不改变vh.所以我想要屏幕的大小,无论浏览器栏,这是什么vh.

在此输入图像描述

Mad*_*adi 10

您可以使用一行代码以像素为单位计算 vh:

let _1vh = Math.round(window.innerHeight / 100)
Run Code Online (Sandbox Code Playgroud)

所以你可以有一个函数:

function vhToPixels (vh) {
  return Math.round(window.innerHeight / (100 / vh)) + 'px';
}
Run Code Online (Sandbox Code Playgroud)

  • 对于移动设备来说情况并非如此,“window.innerHeight”随着 URL 栏的出现和消失而变化。相反,“100vh”是隐藏 URL 栏时的视口高度。这是一篇关于它的[来自 Google 开发人员的好文章](https://developers.google.com/web/updates/2016/12/url-bar-resizing)。 (3认同)
  • document.documentElement.clientHeight 比屏幕高,与 vh 无关。它与页面内容一样高。 (2认同)

Dee*_*ath 6

您可以使用offsetHeightclientHeight以像素为单位获取元素的高度。

offsetHeight属性以像素为单位返回元素的可见高度,包括填充、边框和滚动条,但不包括边距。

clientHeight属性以像素为单位返回元素的可见高度,包括填充,但不包括边框、滚动条或边距。

看到不同

var vhele=document.getElementById('vhele')
function show()
{
    console.log(' clientHeight='+vhele.clientHeight+ 'px'+' , Height with padding and border= ' + vhele.offsetHeight + 'px' );
}
Run Code Online (Sandbox Code Playgroud)
body{
margin:0;
}
#vhele{
  padding:15px;
  border:5px solid red;
}
Run Code Online (Sandbox Code Playgroud)
<div id="vhele" style='height:75vh;background:#AFB'>
                100vh
                
                <button onclick='show()' style='font-size:55px'>
                    Show
                </button>
</div>
Run Code Online (Sandbox Code Playgroud)


小智 2

是不是因为你错过了这个

 <head> 
Run Code Online (Sandbox Code Playgroud)

标签?

   <meta name="viewport" content="width=device-width, initial-scale=1.0">
Run Code Online (Sandbox Code Playgroud)