javascript 无法获取未定义或空引用 IE 的属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18767149/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Unable to get property of undefined or null reference IE
提问by mary glickman
I've inherited a website with some funky code. It held together OK until IE 10 when it started to throw this error:
我继承了一个带有一些时髦代码的网站。它一直保持正常,直到 IE 10 开始抛出此错误:
Unable to get property 'offsetHeight' of undefined or null reference Line: 27 Char: 1 Code: 0 UR
This is the code:
这是代码:
<script type="text/javascript">
function transDiv(){
var theheight=document.getElementById('transcontent').offsetHeight;
document.getElementById('translayer').style.height=theheight+'px';
}
window.onload=transDiv;
setInterval("transDiv()",1); //this handles text resizing through the users browser
</script>
Any thoughts/assistance would be appreciated. Seems to work just fine in Chrome and FF and the client's version of IE (8, ugh).
任何想法/帮助将不胜感激。似乎在 Chrome 和 FF 以及客户端的 IE 版本(8,呃)中工作得很好。
回答by Shadow Wizard is Ear For You
The elements don't have time to load in the 1 millisecond interval. You can change the code to this as a workaround to keep the exact same functionality:
元素没有时间在 1 毫秒间隔内加载。您可以将代码更改为此作为解决方法以保持完全相同的功能:
function transDiv() {
var content = document.getElementById('transcontent');
var layer = document.getElementById('translayer');
if (!content || !layer)
return;
var theheight = content.offsetHeight;
layer.style.height=theheight+'px';
window.setTimeout(transDiv, 1);
}
window.onload = transDiv;
However as it appears to be meant to handle resize, just catch the event instead of using timer. Get rid of the window.setTimeout()
line and add this below the code:
但是,由于它似乎是为了处理调整大小,因此只需捕获事件而不是使用计时器。去掉该window.setTimeout()
行并将其添加到代码下方:
window.onresize = transDiv;