Is this how you incorporate an Onload Event?

笑着哭i 提交于 2019-12-11 07:56:45

问题


I have a quick question. I am trying to incorporate an onload event in HTML5. Here is my code but it refuses to work. Please let me know what I am doing wrong.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>Animation</title>

    <script>
        document.getElementById('videoBackground').onload = function()
        {
            document.body.style.backgroundColor = 'black';
        }
    </script>

    <script type="text/javascript" src="js/animCD.js"></script>    
    <link rel="stylesheet" href="style.css" type="text/css" />

    </head>
    <body>

    <video id="videoBackground" poster="img/loading.png" onload="function()" width="1920" height="1080" preload="auto" onprogress="animCD_onprogress();" onended="animCD_start();">
        <source id="colorVid_mp4" type="video/mp4" src="img/luther_color.mp4">      
    </video>

回答1:


Specifying someElement.onload = function() { } is how you create an onload handler in a general sense. The reason your doesn't work is that your script block comes before the element in question and runs immediately, at which point document.getElementById() can't find that element because it hasn't been parsed yet.

You can fix this by moving the script block to somewhere after the element (many people put their scripts at the end of the body), or by calling it in an onload handler for the page:

window.onload = function() {
    document.getElementById('videoBackground').onload = function() {
        document.body.style.backgroundColor = 'black';
    }
};

Although the page/window's onload should be called after all content is loaded, so I'm not sure that there's any point creating more onload handlers from there.

I notice you also have an onload="function()" attribute in your html. That is another way to specify a handler, although inline event attributes are not the preferred way to do things, but you'd need to put an actual function name onload="someFunction()" to call a named function defined elsewhere, or put the code directly:

<video ... onload="document.body.style.backgroundColor='black';" ...>



回答2:


At the point where you are executing getElementById('videoBackground') the element with the id videoBackground doesn't exist yet.

Either move the script below where you created the videoBackground element or run the script after the DOM loads using document.onload.



来源:https://stackoverflow.com/questions/13486094/is-this-how-you-incorporate-an-onload-event

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!