代码之家  ›  专栏  ›  技术社区  ›  0xtuytuy

获取页面内容的高度

  •  0
  • 0xtuytuy  · 技术社区  · 11 年前

    我正在尝试获取网页主体的高度。我希望它是当页面以100%缩放加载到高清屏幕上时的值。

    这样做的目的是改变元数据中的视口,并能够强制移动浏览器一次加载整个页面,并阻止设计的响应性。

    function calculateHeightOfBody() {
    var body = document.body,
    html = document.documentElement;
    
    var height = Math.max( body.scrollHeight, body.offsetHeight, 
                       html.clientHeight, html.scrollHeight, html.offsetHeight );
    
    viewport = document.querySelector("meta[name=viewport]");
    viewport.setAttribute('content', /*'width='+width+',*/ 'height='+height);
    
    alert('height is ' + height);
    

    我有这个功能,它可以工作,但无论我是在电脑上还是在电话上打开页面,它都会给我两个不同的值。

    在一台有高清屏幕的电脑上,我得到了944,在手机上我得到了2044.944是正确的值。

    谢谢

    1 回复  |  直到 11 年前
        1
  •  2
  •   Hayden Schiff    11 年前

    问题是你有一个高像素密度的手机,它可以以增加的像素比例渲染网页。高度除以 window.devicePixelRatio 为了解释这一点。

    注意:我不认为你的身高测量方法特别理想。不要只选择5个值中的最大值,而应该只使用一个值。可能 window.innerHeight 会成功吗?