Javascript 单击图像后如何播放/启动 YouTube 视频?

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

How to play/start youtube video after clicking on an image?

javascriptjqueryapiyoutubeclick

提问by Grozav Alex Ioan

I have an image and I want to start a youtube video only after I click the image. How can I do this?

我有一张图片,我想在点击图片后才开始播放 YouTube 视频。我怎样才能做到这一点?

Thanks a lot!

非常感谢!

采纳答案by Laurent Zuijdwijk

Have a look at:

看一下:

Youtube API examples

Youtube API 示例

the code will be something like this:

代码将是这样的:

function onPlayerReady(event) {
    $('img').click(function() { 
        ytPlayer.playVideo();
    });
}

回答by Shahadat

.click()JQuery event handler:

.click()JQuery 事件处理程序:

$("#clickMe").click(function(){
  $("#iframe")[0].src += "&autoplay=1";
  ev.preventDefault();
});

回答by Marek

Another approach - switch iframe SRC (URL) with "?autoplay=1" version.

另一种方法 - 使用“?autoplay=1”版本切换 iframe SRC (URL)。

<a href="#" id="clickMe">PLAY</a>

<iframe id="iframe" width="1280" height="720" src="//www.youtube.com/embed/F0naUkyEkmM" 
            data-autoplay-src="//www.youtube.com/embed/F0naUkyEkmM?autoplay=1"></iframe>

jQuery:

jQuery:

jQuery("#clickMe").on('click',function(){
    var vi = jQuery("#iframe");
    vi.attr("src", vi.data("autoplay-src") );
});

回答by Ajithkumar S

I think this will help you. Working fine for me.

我认为这会对你有所帮助。对我来说工作得很好。

$('.trigger').on('click', function () {
    $(".video")[0].src += "1";
});
<a href="#" class="trigger">Click</a>
        
<iframe class="video" src="https://www.youtube.com/embed/HJX71gFz_do?autoplay=" frameborder="0" allowfullscreen></iframe>

回答by Emil Diego

adding autoplay=1 only seems to work the first time. I am using a start/stop button and when i click it the first time, i add autoplay=1. Then when i click it again I remove the autoplay=1. That works fine.

添加 autoplay=1 似乎只在第一次工作。我正在使用开始/停止按钮,当我第一次单击它时,我添加了 autoplay=1。然后当我再次单击它时,我删除了自动播放 = 1。这很好用。

but when i try to start it again (adding autoplay=1), it won't start.

但是当我尝试再次启动它(添加 autoplay=1)时,它不会启动。