如何使用 vanilla Javascript 暂停嵌入的 Youtube 视频? [英] How can I pause an embedded Youtube video with vanilla Javascript?

查看:24
本文介绍了如何使用 vanilla Javascript 暂停嵌入的 Youtube 视频?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在没有视频相关事件触发器的情况下暂停嵌入 iframe 的 YouTube 视频.

I try to pause an iframe embedded YouTube video without a video-related event trigger.

我已阅读 youtube 嵌入式 api这个答案这个,这就是我所拥有的到目前为止(由于 CORS 问题,视频无法在片段中播放,但我想这并不重要.):

I have read the youtube embedded api, this answer and this one and here is what I have so far (the video wont play in the snippet because of a CORS issue, but I guess it doesn't really matter.):

<iframe id="video1" width="560" height="315" src="http://www.youtube.com/embed/JFBUJ6kNl28" frameborder="0" allowfullscreen></iframe>

<script type="text/javascript">
  //youtube api to pause video when changing section
  var tag = document.createElement('script');
  tag.src = "//www.youtube.com/iframe_api";
  var firstScriptTag = document.getElementsByTagName('script')[0];
  firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
  var player = false

  function onYouTubeIframeAPIReady() {
    player = new YT.Player('video1', {});
  }

  function jump() {
    console.log(player);
    if (player) {
      player.pauseVideo()
    }
  }
</script>
<button type="button" onclick="jump()" name="button">pause button</button>

我错过了什么?当我记录它时,播放器对象在那里,但它向我抛出一个 player.pauseVideo() is not a function

What am I missing? The player object is there when I log it but it throws me a player.pauseVideo() is not a function

推荐答案

我找到了解决方案:如这个答案,需要在视频网址中添加?enablejsapi=1

I found the solution: as described in this answer, you need to add ?enablejsapi=1 to the video URL

A:您必须在 URL 末尾添加 ?enablejsapi=1:/embed/vid_id?enablejsapi=1

A: You have to add ?enablejsapi=1 at the end of your URL: /embed/vid_id?enablejsapi=1

不知何故,它不适用于我的代码片段,但适用于我的真实情况.

Somehow, it doesn't work with my snippet but works in my real case.

这篇关于如何使用 vanilla Javascript 暂停嵌入的 Youtube 视频?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆