【问题标题】:Getting height and width of body or window of web page获取网页正文或窗口的高度和宽度
【发布时间】:2010-07-20 08:57:11
【问题描述】:

根据我所处的 IE8 模式(怪癖或标准),我得到不同的高度和宽度值。我尝试过标准的 javascript 和 jquery,但都返回不同的结果。

在怪癖中

$('body').width = 1239  
$('body').height = 184  
document.body.clientWidth = 1231  
document.body.clientHeight = 176  

在标准中

$('body').width = 1260  
$('body').height = 182  
document.body.clientWidth = 1254  
document.body.clientHeight = 176

任何想法如何通过 IE8 的模式获得不变的值。

感谢您的建议。

【问题讨论】:

    标签: javascript jquery html


    【解决方案1】:

    也许问题是由于滚动条包含在宽度和高度中,无论它们是否存在。我没有 IE(在 Mac 上)所以无法验证。

    但是,我可以告诉你在我的项目jQuery Lightbox 中什么是有效的,我没有这样的问题。我们在其中使用以下代码:

    // Make the overlay the size of the body
    var $body = $(this.ie6 ? document.body : document); // using document in ie6 causes a crash
    $('#lightbox-overlay').css({
     width:  $body.width(),
     height:  $body.height()
    });
    
    // ... some code ...
    
    // Get the window dimensions
    var $window = $(window);
    var wWidth  = $window.width();
    var wHeight = $window.height();
    

    并且覆盖显示正确。与原生结果相比,我会相信 jQuery 的宽度和高度结果,因为 jQuery 自然应该考虑到浏览器的任何怪癖。

    请务必注意,由于某种原因,上面的灯箱脚本倾向于使用 $(document) 而不是 $(document.body) - 我不记得了,抱歉 :O - 所以也许这也解决了问题?

    【讨论】:

      【解决方案2】:

      只是一个快速的镜头。尝试给你的身体#page:

      function getPageHeight() {
          var pageHeight = document.getElementById('page').offsetHeight;
          var pageWidth = document.getElementById('page').offsetWidth;
      
          alert(pageHeight);
          alert(pageWidth);
      }
      

      【讨论】:

      • 还是没有运气。身高也有点奇怪。标准高度 = 大约 200,怪癖大约是 800。
      • 您能解释一下为什么需要在 ie8 中区分 quirks 和standardsmode 吗?
      • 我不想,但我需要页面在两种模式下显示相同。
      【解决方案3】:

      试试这个:

      var viewport = {
          width : $(window).width(),
          height : $(window).height()
      };
      
      var width = viewport.width;
      var height = viewport.height;
      

      【讨论】:

        猜你喜欢
        • 2014-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-11
        • 2013-11-29
        相关资源
        最近更新 更多