简体   繁体   中英

Everything disappears on Javascript load

When I start the function via Body onload="playVideo();" and after the video ends, everything on the website disappears, except the background Video.

My function (It starts a random video):

function playVideo() {
  var videos = [
    '1.mp4',
    'Lil Pump - _Gucci Gang_ (Official Music Video).mp4',
  ];
  var reloadCss = '<link rel="stylesheet" href="video.css"/>'
  var index = Math.floor(Math.random() * videos.length);
  var html = '<video autoplay="autoplay" preload="true" id="Background" onended="playVideo()"><source src="Videos/' + videos[index] + '" type="video/mp4"></video>';
  document.write(html);
  document.write(reloadCss);
}

Your page is being replaced with the video html you are placing with document.write.

W3schools says this about document.write:

The write() method writes HTML expressions or JavaScript code to a document.

The write() method is mostly used for testing: If it is used after an HTML document is fully loaded, it will delete all existing HTML.

You could use the jQuery append function to add dynamic html like you are trying to do. See the snippet below for a quick example. Your video and script tag just show up as white space, but you can see that the append method just adds html instead of replacing the page like the comments suggested.:

You could also use the javascript appendChild() function if you want to use vanilla javascript.

 $(function(){ //Run your playvideo function on page load playVideo(); }) function playVideo() { var videos = [ '1.mp4', 'Lil Pump - _Gucci Gang_ (Official Music Video).mp4', ]; var reloadCss = '<link rel="stylesheet" href="video.css"/>' var index = Math.floor(Math.random() * videos.length); var html = '<video autoplay="autoplay" preload="true" id="Background" onended="playVideo()"><source src="Videos/' + videos[index] + '" type="video/mp4"></video>'; //Use append rather than setting the document html to add //elements. Otherwise the whole page html will be replaced $content = $(".content"); $content.append(html); $content.append(reloadCss); $content.append("<p>More content</p>"); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <html> <body> <div class="content"> <p>Content</p> </div> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM