JavaScript:Internet Explorer中的document.getElementById()出错

Ana*_*mar 1 javascript internet-explorer

我目前在JavaScript中遇到错误.代码如下

function loader() {
    size = window.innerWidth;
    size = size - 300;
    mainj = document.getElementById('main1');
    mainj.style.left = size.toString() + 'px';
    submainj = document.getElementById('submain1');
    submainj.style.left = size.toString() + 'px';
    size = mainj.style.top + 26;
    document.getElementById('submain1').style.top = size.toString() + 'px';
}
onload = loader();
Run Code Online (Sandbox Code Playgroud)

该错误仅在Internet Explorer中出现,并且代码在Firefox中完美运行.错误显示在第五行,错误是

Message: Object required
Line: 34
Char: 1
Code: 0
URI: http://localhost/home.php
Run Code Online (Sandbox Code Playgroud)

第34行是代码中给出的第5行 - 'mainj.style.left .....'如何解决这个问题?

Nea*_*eal 8

确保你有一个ID =的DOM元素main1

如果它不存在,那么您的代码将返回错误.

你能做的是有条件的:

if(mainj  !== undefined) {  //if mainj is a real object
   //do code with mainj
}
Run Code Online (Sandbox Code Playgroud)

还可以尝试在代码中使用局部变量(在带有单词的变量之前var),这样它们就不会进入全局范围.