IE的两个问题
分类:Javascript
上次提到IE下通过window属性定义变量的bug,最近又遇到两个问题:
IE dom方法赋值变量调用错误
如下代码:
var s = document.getElementById;
alert(typeof s);
var el = s.call(document, 'test');
el.innerHTML = "ok";
应该alert出什么?el里的文字是?
按道理应该alert出 function,文字是ok,但在ie下却alert 出 object,IE7/8下文字是ok,ie6下却报错
“object doesn’s support this property or method”
因此应避免将dom方法直接付给变量,再来看看另一问题
IE 的<html>元素border问题
在计算元素offset时经常用到docuementElement.offsetHeight,documentElement.scrollTop
比如要实现一个元素固定居于浏览器右下角,ie6下通过脚本实现:
var el = document.getElementById('test'),
htmlEl = document.documentElement;
function rb() {
el.style.top = htmlEl.scrollTop + (window.innerHeight||htmlEl.offsetHeight) - 50+'px';
}
window.onscroll=rb;
window.onresize=rb;
offsetHeight是指整个元素的高度(border box),在ie下html元素错误的box模型,offsetHeight返回的也是窗的高度
看下测试demo发现ie无限向下滚动,原因在ie下html元素有2px的border,而元素定位是相对body的这样每次计算都多出2px
将offsetHeight改为clientHeight ok!clientheight是元素内容区域的高度(padding box)
以后处理基于<html>元素定位问题时需要留意这2px的box
最后看看jquery offset方法的实现也是对这个问题进行了处理,offset.js

JavaScript document object provides getElementById function that returns the HTML object according to the specified id of the element. offsetHeight..You can learn more about these properties from the tutorial link provided at the bottom and top of this sample…Try the sample below to learn the working of JavaScript code for retrieving the height of the HTML div element dynamically ..