javascript - 单击按钮时更改嵌入式 youtube 视频中的时间

标签 javascript jquery html video youtube-api

我想嵌入一个 youtube 视频并提供按钮,当您单击这些按钮时,它们会转到视频中的特定时间并从那里继续播放。 我试过使用 jquery 并更改“src”属性,如下所示:

原始出处:

<iframe src="http://www.youtube.com/embed/PjDw3azfZWI?&t=5m30s&rel=0&amp">

JS:

$("#link1").click(function() {
    $("#video").attr("src", "http://www.youtube.com/embed/PjDw3azfZWI?&t=10m30s&rel=0&amp");
});

这导致浏览器在我单击按钮时刷新。

链接到我的想法的图像:http://i.imgur.com/sCFZSIn.png .单击按钮应使视频跳转到指定的时间。

最佳答案

您不应该重新加载 iframe 来控制视频;使用 Javascript API 方法。在这里查看 seekTo:https://developers.google.com/youtube/iframe_api_reference#Playback_controls

基本上,加载 iframe 后,JS API 将调用 onYouTubeIframeAPIReady(),您可以在其中构建 YouTube 播放器对象。然后您可以使用该播放器引用来控制视频,例如 player.seekTo()。

您仍然可以使用您的 iframe,如 this section 底部所述:

As mentioned in the Getting started section, instead of writing an empty element on your page, which the player API's JavaScript code will then replace with an element, you could create the tag yourself.

...

If you do write the tag, then when you construct the YT.Player object, you do not need to specify values for the width and height, which are specified as attributes of the tag, or the videoId and player parameters, which are are specified in the src URL.

您的代码缺少的部分是 YT.Player 对象,您必须在上述回调方法中构造该对象。这提供了对播放器控件的访问。

这是一个 Fiddle演示:

var player, seconds = 0;
function onYouTubeIframeAPIReady() {
    console.log("player");
    player = new YT.Player('player', {
        events: {
          'onReady': onPlayerReady
        }
      });
}

function onPlayerReady(event) {
    event.target.playVideo();
}

function seek(sec){
    if(player){
        seconds += sec;
        player.seekTo(seconds, true);
    }
}

您可以将这段代码放在一个单独的脚本中,但要确保它在根范围内(例如在您的 head 标记中),而不是将其放在 onLoad 处理程序中。

关于javascript - 单击按钮时更改嵌入式 youtube 视频中的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26257395/

相关文章:

javascript - 如何使用 jQuery 减少 `li` 中 `select2` 的填充?

javascript - 删除 Fetch API 默认超时

javascript - 如何进行二进制数的按位运算?

javascript - 如何隐藏第一个表中的第一个元素?

javascript - ReactJS 在 HTML 中创建额外的跨度

javascript - 显示带有复选框的 jquery <div>

html - 为什么背景图像在移动设备上不会改变?

javascript - JavaScript Canvas 上的平滑按键动画

javascript - 当特定的 ajax 请求完成时做某事

javascript - 如何启用和禁用 Ajax.Actionlink