在javascript中占用怪癖模式的元素的宽度?

chr*_*off 6 html javascript css

我一直在扫描所有流行的js库,但我找不到一个具有宽度函数的DOM元素实际上在Internet Explorer中占用了怪癖模式.问题是当使用怪癖模式时,填充和边框不会计入宽度.据我所知,当doctype被省略或doctype设置为html 3.2时会发生这种情况.

显然我可以将doctype设置为符合标准的东西,但是这个脚本可以嵌入任何地方,所以我无法控制doctype.

将问题分解为更小的部分:

1)你如何检测怪癖模式?2)从元素中提取边框和填充以补偿的最佳方法是什么?

原型示例:

<html>
<head>
</head>
<body>

<div id="mydiv" style="width: 250px; pading-left: 1px; border: 2px black solid">hello</div>

<script>
  alert($('mydiv').getWidth())
</script>

</body>
</html>
Run Code Online (Sandbox Code Playgroud)

结果:

253(ff)250(即)

提前致谢!

paw*_*wel 2

@1

document.compatMode
Run Code Online (Sandbox Code Playgroud)

“CSS1Compat”表示“标准模式”,“BackCompat”表示“怪异模式”。

@2

HTML 元素的 offsetWidth 属性给出了它在屏幕上的宽度(以像素为单位)。

<div id="mydiv" style="width: 250px; padding-left: 1px; border: 2px black solid">hello</div>

document.getElementById('mydiv').offsetWidth
//255 (standards) 250 (quirks)
Run Code Online (Sandbox Code Playgroud)

补偿 IE quirksmode 宽度的函数必须检查渲染模式,然后向宽度添加边框和填充;

function compensateWidth( el, targetWidth ){

    var removeUnit = function( str ){
        if( str.indexOf('px') ){
            return str.replace('px','') * 1;
        }
        else { //because won't work for other units... one may wish to implement 
            return 0;
        }
    }
    if(document.compatMode && document.compatMode=="BackCompat"){
        if(targetWidth && el.offsetWidth < targetWidth){
            el.style.width = targetWidth;
        }
        else if (el.currentStyle){
            var borders = removeUnit(el.currentStyle['borderLeftWidth']) + removeUnit(el.currentStyle['borderRightWidth']);
            var paddings = removeUnit(el.currentStyle['paddingLeft']) + removeUnit(el.currentStyle['paddingRight']);
            el.style.width = el.offsetWidth + borders + paddings +'px';
        }
    }

}
Run Code Online (Sandbox Code Playgroud)

现在有两种使用方法:

var div = document.getElementById('mydiv')
// will try to calculate target width, but won't be able to work with units other than px
compensateWidth( div );

//if you know what the width should be in standards mode
compensateWidth( div, 254 );
Run Code Online (Sandbox Code Playgroud)