Javascript onload 不起作用(“未捕获的类型错误:无法设置 null 的属性‘document.body’”)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/26989980/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 06:47:35  来源:igfitidea点击:

Javascript onload isn't working ("Uncaught TypeError: Cannot set property 'document.body' of null ")

javascriptnullonload

提问by Star Light

Here is my codes:

这是我的代码:

Javascript:

Javascript:

document.body.onload = function() {
    function UP() {//?n hi?n nút UP
        if(window.pageYOffset > window.innerHeight)
            document.getElementById('UP').style.display = "block";
    }
}

HTML tag:

HTML 标签:

<button id="UP" onclick="toTop(350);"></button>

CSS style:

CSS样式:

#UP {display: none;}

My idea is when I scroll down, then UP button will appear. But don't know why, it won't, it even return the error: "Uncaught TypeError: Cannot set property 'document.body' of null". Of couse, I did change other script like this:

我的想法是当我向下滚动时,会出现 UP 按钮。但不知道为什么,它不会,它甚至返回错误:“未捕获的类型错误:无法设置 null 的属性 'document.body'”。当然,我确实像这样更改了其他脚本:

function getReady() {
    UP();
}
function UP() {//?n hi?n nút UP
    if(window.pageYOffset > window.innerHeight)
        document.getElementById('UP').style.display = "block";
}

HTML tag:

HTML 标签:

<body onload="getReady();">
    <button id="UP" onclick="toTop(350);"></button>
</body>

It is even more terrible. When I load site, I didn't see onload attr of body tag and the browser didn't return any error for me.

更可怕的是。当我加载站点时,我没有看到 body 标签的 onload attr 并且浏览器没有为我返回任何错误。

Some other infomation: I develop on both side, Cr & FF, it all says a same problem. And I'm working on Wordpress source.

其他一些信息:我在两边开发,Cr & FF,都说同样的问题。我正在研究 Wordpress 源代码。

回答by somethinghere

Just to clarify @laruiss and explain what is going on, lets start with your code:

只是为了澄清@laruiss 并解释发生了什么,让我们从您的代码开始:

/* body.onload is not recommended, window.onload is. But thats not the main issue*/
window.onload = function() {
    /* You are declaring a function here. Very important: 
     * its a declaration, NOT a function call 
     */
    function UP() {
        if(window.pageYOffset > window.innerHeight)
            document.getElementById('UP').style.display = "block";
    }
    /* So if you want to execute ('call') your function, you have two options:
     * - Remove the declaration around your function aka `function UP(){` and the ending `}`
     * - Call the function here. To make your code work instantly, lets do that.
     */
    UP();
}

When using the onload event, you are actually doing the right thing. True, it's not recommendedto actually do that in your DOM, but it should work. The biggest issue that DOM load is subjective. Some browsers will consider the body loaded as soon as the content is in, others will wait for images, and older IE versions won't fire it all! So if you use the recommended window.onload, you should be fine, as it will fire as soon as the DOM is ready. There is another great event for this you might want to consider, which is DOMContentLoaded, but its not as widely supported. Theres a bit more (by clicking through as well) here: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onload

使用 onload 事件时,您实际上是在做正确的事情。确实,不建议在您的 DOM 中实际执行此操作,但它应该可以工作。DOM 加载的最大问题是主观的。一些浏览器会在内容一进入就考虑加载正文,其他浏览器会等待图像,而较旧的 IE 版本不会全部触发!所以如果你使用推荐的window.onload,你应该没问题,因为它会在 DOM 准备好后立即触发。您可能需要考虑另一个重要事件,即DOMContentLoaded,但它没有得到广泛支持。这里还有更多(通过点击):https: //developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers.onload

I would also like to add that even though you put your button to display, its has no content so it could appear either empty or if you are resetting your button styles, not at all. Something to keep in mind.

我还想补充一点,即使您将按钮显示出来,它也没有内容,因此它可能显示为空,或者如果您正在重置按钮样式,则根本没有。要记住的事情。

回答by laruiss

There are a few problems with your code:

您的代码存在一些问题:

  • document.body.onloadshould be replaced by window.onload, as said in the comments
  • in the onload function, you define a function, but you don't invoke it...
  • document.body.onload应该替换为window.onload,如评论中所述
  • 在 onload 函数中,您定义了一个函数,但没有调用它...

So

所以

document.body.onload = function() {
    function UP() {//?n hi?n nút UP
        if(window.pageYOffset > window.innerHeight)
            document.getElementById('UP').style.display = "block";
    }
}

Should be replaced by:

应改为:

window.onload = function up() { // Could be anonymous, of course, but should not
    if(window.pageYOffset > window.innerHeight)
        document.getElementById('UP').style.display = "block";
}

回答by Amitesh

To answer your question "My idea is when I scroll down, then UP button will appear." i think you should register 'scroll' event on your scrollable container div. 'body/window.onload' function will be fired just once and hence it will not fullfill the requirement. Here is how you can proceed (working fiddle)

回答你的问题“我的想法是当我向下滚动时,就会出现向上按钮。” 我认为您应该在可滚动容器 div 上注册“滚动”事件。'body/window.onload' 函数只会被触发一次,因此它不会满足要求。这是您可以继续的方法(工作小提琴

<div id="container" onscroll="handleScroll(this)">
    <button id="UP" onclick="toTop(350);">Go to Top</button>
     Scroll me</br>....scrollable content

Javascript

Javascript

function handleScroll (obj) {
    var displayVal = "block";
    if (obj.scrollTop == "0") {
        displayVal = "none";
    }
    document.getElementById('UP').style.display = displayVal;
};