【问题标题】:Why does document.body.offsetHeight + document.body.bottomMargin not equal document.documentElement.offsetHeight为什么 document.body.offsetHeight + document.body.bottomMargin 不等于 document.documentElement.offsetHeight
【发布时间】:2014-03-14 10:48:47
【问题描述】:

我正在尝试锻炼 iFrame 的高度,但不明白为什么

document.body.offsetHeight + document.body.bottomMargin 

不等于

document.documentElement.offsetHeight

当所有其他边距设置为零且底部边距的值低于 16 像素时。

一旦下边距超过 16px,上述两个值在 FireFox 中相等,在 Chrome 中则在 1px 以内。

奇怪的是这个问题不会影响宽度计算。

【问题讨论】:

    标签: javascript dom


    【解决方案1】:

    经过大量挖掘,我想出了这个来解决问题。

    function getIFrameHeight(){
        function getComputedBodyStyle(prop) {
            return parseInt(
                document.defaultView.getComputedStyle(document.body, null),
                10
            );
        }
    
        return document.body.offsetHeight +
            getComputedBodyStyle('marginTop') +
            getComputedBodyStyle('marginBottom');
    }
    

    以及 IE8 及以下版本的扩展版本。

    function getIFrameHeight(){
        function getComputedBodyStyle(prop) {
            function getPixelValue(value) {
                var PIXEL = /^\d+(px)?$/i;
    
                if (PIXEL.test(value)) {
                    return parseInt(value,base);
                }
    
                var 
                    style = el.style.left,
                    runtimeStyle = el.runtimeStyle.left;
    
                el.runtimeStyle.left = el.currentStyle.left;
                el.style.left = value || 0;
                value = el.style.pixelLeft;
                el.style.left = style;
                el.runtimeStyle.left = runtimeStyle;
    
                return value;
            }
    
            var 
                el = document.body,
                retVal = 0;
    
            if (document.defaultView && document.defaultView.getComputedStyle) {
                retVal =  document.defaultView.getComputedStyle(el, null)[prop];
            } else {//IE8 & below
                retVal =  getPixelValue(el.currentStyle[prop]);
            } 
    
            return parseInt(retVal,10);
        }
    
        return document.body.offsetHeight +
            getComputedBodyStyle('marginTop') +
            getComputedBodyStyle('marginBottom');
    }
    

    【讨论】:

    • 难道没有一个 easy 解决方案:-/
    • 很想知道你是否找到了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-03
    • 2010-11-11
    • 2010-12-22
    相关资源
    最近更新 更多