Javascript 如何为 YouTube 视频添加启动画面/占位符图像

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

How to add a splash screen/placeholder image for a YouTube video

javascriptjqueryhtmlcssyoutube

提问by Stuart

I have a website that includes a lot of embedded YouTube videos; currently these are loaded simultaneously which, of course, causes the site to run extremely slowly when initially loaded.

我有一个网站,其中包含许多嵌入的 YouTube 视频;目前这些是同时加载的,这当然会导致网站在最初加载时运行速度极慢。

What is the best way to load an image as a placeholder/splash screen instead of the video iframe?

将图像加载为占位符/启动画面而不是视频 iframe 的最佳方法是什么?

The image will need to be replaced by the YouTube iframe only when clicked(this should only be loaded when requested), thus reducing the file size of the website dramatically. I have found some similar questions before but they seem to recommend using CSS and jQuery to alter the visibility of the video. This doesn't work in this instance because the video player will still load in the background.

只有在点击时,图片才需要被 YouTube iframe 替换(这应该只在请求时加载),从而大大减少了网站的文件大小。我之前发现过一些类似的问题,但他们似乎建议使用 CSS 和 jQuery 来改变视频的可见性。这在这种情况下不起作用,因为视频播放器仍将在后台加载。

I appreciate any help/suggestions.

我感谢任何帮助/建议。

回答by Wesley Murch

It should be pretty straight forward, try something like this:

它应该很简单,尝试这样的事情:

<img src="placeholder.jpg" data-video="http://www.youtube.com/embed/zP_D_YKnwi0">
$('img').click(function(){
    var video = '<iframe src="'+ $(this).attr('data-video') +'"></iframe>';
    $(this).replaceWith(video);
});

Demo: http://jsfiddle.net/2fAxv/1/

演示:http: //jsfiddle.net/2fAxv/1/

For youtube videos, add &autoplay=1to the URL if you want them to play when the image is clicked.

对于 youtube 视频,&autoplay=1如果您希望在单击图像时播放它们,请添加到 URL。