0

The code that i am working on is this-

var winW;
if (document.body && document.body.offsetWidth) {
 winW = document.body.offsetWidth;
}
if (document.compatMode=='CSS1Compat' &&
    document.documentElement &&
    document.documentElement.offsetWidth ) {
 winW = document.documentElement.offsetWidth;
}
if (window.innerWidth && window.innerHeight) {
 winW = window.innerWidth;
}
if (winW = 1265) {
function setPosition()
{
document.getElementById("wblogo").style.left="1050px";
}
}

The code works perfectly when i use it with the onload event in the body tag.

But i want to use this when the page is being loaded. So i used the following code-

var winW;
if (document.body && document.body.offsetWidth) {
 winW = document.body.offsetWidth;
}
if (document.compatMode=='CSS1Compat' &&
    document.documentElement &&
    document.documentElement.offsetWidth ) {
 winW = document.documentElement.offsetWidth;
}
if (window.innerWidth && window.innerHeight) {
 winW = window.innerWidth;
}
if (winW = 1265) {
document.getElementById("wblogo").style.left="1050px";
}

But this code doesn't work. Please help.

4

1 回答 1

3

我的猜测是,当您删除 时onload,您将脚本留在head了文档的部分中。您尝试使用的元素 ( document.body, 您的wblogo元素)尚不存在,因此代码无法与它们交互。当您使用onload时,您的代码并没有立即运行,而是在加载所有图像等之后的页面加载周期很晚,因此元素确实存在

相反,将您的代码放在文档末尾script的标签中,就在结束标签之前。这样,您尝试使用的元素就会存在。</body>

更多的:

于 2012-12-16T08:33:12.917 回答