<分区>
标签 javascript jquery html css
<分区>
当我通过 Body onload="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>';
document.write(html);
document.write(reloadCss);
}
最佳答案
您的页面将替换为您使用 document.write 放置的视频 html。
W3schools这是关于 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.
您可以像您尝试的那样使用 jQuery 附加函数添加动态 html。请参阅下面的代码片段以获取快速示例。您的视频和脚本标签只是显示为空白,但您可以看到 append 方法只是添加了 html,而不是像评论建议的那样替换页面。:
您还可以使用 javascript appendChild() function如果你想使用 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>
关于javascript - 一切都在 Javascript 加载时消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46992378/
相关文章:
javascript - 如何在不创建格式错误的 HTML 标签的情况下分解字符串?
javascript - polymer 2.0 : why do we need an anonymous function when imperatively adding listener
php - 从客户端向服务器发送变量 | JSON 与 POST
javascript - 使用 javascript/jQuery 获取 data-* 属性列表
html - 删除较小视口(viewport)上的 CSS 网格值
javascript - 如何禁用 DocuSign 基于浏览器的地理位置弹出对话框
jquery - 从 jquery ajax 的 XML 格式响应中读取值
javascript - jQuery $().css ("content") 在 IE9 中返回字符串 "normal"