【问题标题】:Pausing an Youtube iframe with js使用 js 暂停 Youtube iframe
【发布时间】:2018-03-06 13:53:53
【问题描述】:

我想创建一个按钮来暂停自动播放的 youtube 视频。

这是 iframe:

<iframe id="music" width="0" height="0" src="https://www.youtube.com/embed/v_FucrYWy3k?rel=1&amp;controls=0&amp;showinfo=0&amp;start=1&autoplay=1&enablejsapi=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>

这是按钮:

  <button onclick="mute()" type="button" name="button">mute</button>

这就是 JS:

function mute(){
  var myVideo =  document.getElementById('music');
  myVideo.pauseVideo();
}

我错过了什么?

【问题讨论】:

  • 你在哪里定义iframe,你为什么要调用getElementById('music'),这是同一iframe上iframe的id?您的控制台中是否有任何错误?
  • document.getElementById()... 对于初学者。
  • 猜我需要使用 document.getElementById,但这也不起作用...
  • @Ionut 刚改成document.getElementById()。还是行不通。错误:script.js:110 Uncaught TypeError: myVideo.pauseVideo is not a function at mute (script.js:110) at HTMLButtonElement.onclick (index.html:30) mute @ script.js:110 onclick @ index.html:30

标签: javascript html


【解决方案1】:

看来,对于当前的 Youtube API,您需要做的不仅仅是将 enablejsapi 作为 get 参数添加到嵌入中。您实际上必须包含来自 here 的 API 脚本,并且还必须使用自定义方法。你可以看看下面的代码或运行这个工作JSFiddle

<iframe id="music" width="310" height="310" src="https://www.youtube.com/embed/v_FucrYWy3k?rel=1&amp;controls=1&amp;showinfo=0&amp;start=1&autoplay=1&enablejsapi=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
<button id='button' type="button" name="button">mute</button>

还有JS代码:

//create the script for the API and append it to the DOM
var tag = document.createElement('script');
tag.src = 'https://www.youtube.com/iframe_api';
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

var player;

function onYouTubeIframeAPIReady() {
  player = new YT.Player('music', {
    events: {
      'onReady': onPlayerReady
    }
  });
}

function onPlayerReady(event) {
  document.getElementById('button').addEventListener('click', function() {
    player.pauseVideo();
  })
}

这一切都在文档中 here

【讨论】:

    【解决方案2】:

    【讨论】:

    • 仅链接的答案通常是 Stack Overflow 上的frowned upon。随着时间的推移,链接可能会萎缩并变得不可用,这意味着您的答案将来对用户毫无用处。如果您可以在实际帖子中提供答案的一般详细信息,并引用您的链接作为参考,那将是最好的。
    猜你喜欢
    • 2012-11-05
    • 2017-04-11
    • 2012-10-06
    • 2017-07-18
    • 1970-01-01
    • 2016-08-02
    • 2016-01-25
    • 2021-07-07
    • 2014-06-11
    相关资源
    最近更新 更多