处理关键事件时,使用Youtube iframe API

Handle key events when using Youtube iframe API

本文关键字:使用 Youtube iframe API 事件 处理      更新时间:2023-09-26

我正在寻找一个解决方案,如何处理关键事件时运行Youtube视频在我的应用程序使用Youtube iframe API。不幸的是找不到。我看过这个文档https://developers.google.com/youtube/iframe_api_reference#Events,但似乎玩家没有触发任何与键相关的事件(例如:onkeydown, keypress, keyup)。

我尝试将事件直接添加到提供的代码中,但它不起作用。

 var tag = document.createElement('script');
      tag.src = "https://www.youtube.com/iframe_api";
      var firstScriptTag = document.getElementsByTagName('script')[0];
      firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);
      // 3. This function creates an <iframe> (and YouTube player)
      //    after the API code downloads.
      var player;
      function onYouTubeIframeAPIReady() {
        player = new YT.Player('trailer_video', {
          height: '390',
          width: '640',
          videoId: 'M7lc1UVf-VE',
          events: {
            // 'onReady': onPlayerReady,
            'onStateChange': onPlayerStateChange,
            'onkeydown': myfunction    // custom event 
          }
        });
      }

有什么方法可以处理键事件,特别是当箭头键被按下时?

p。S:我不知道我可能在这里错了,但通常当我在视频缓冲时按箭头键时,我看到点链在移动,这给了我一个提示,玩家确实检测到这些事件并做出反应。

<标题> 更新问题

下面的答案建议,这当然是在某种程度上的解决方案,但由于Youtube也处理左和右箭头键事件,它可以使用当光标在视频上,我关心的是,我怎么能处理向上和向下箭头键的事件,这不是由Youtube处理,只有当光标不在视频上,如果我实现一个自定义事件处理程序。

这取决于你想要完成什么。但是你的问题的答案是,"我是否有办法处理键事件,特别是当箭头键被按下时?"是yes。下面是一个使用左方向键和右方向键的自定义倒带/快进功能的示例:

https://jsfiddle.net/xoewzhcy/3/

<div id="video"></div>
function embedYouTubeVideo() {
    player = new YT.Player('video', {
         videoId: 'M7lc1UVf-VE'
    });
}
function rewind() {
    var currentTime = player.getCurrentTime();
    player.seekTo(currentTime - 30, true);
    player.playVideo();
}
function fastforward() {
    var currentTime = player.getCurrentTime();
    player.seekTo(currentTime + 30, true);
    player.playVideo();  
}
$(function(){
    // embed the video
    embedYouTubeVideo();
    // bind events to the arrow keys
    $(document).keydown(function(e) {
        switch(e.which) {
            case 37: // left (rewind)
                rewind();
            break;
            case 39: // right (fast-forward)
                fastforward();
            break;
            default: return; // exit this handler for other keys
        }
        e.preventDefault(); // prevent the default action (scroll / move caret)
    });
});

注意:注意当你专注于嵌入的视频(即,你点击YouTube播放按钮或点击进入YouTube iframe以任何方式)。因为,你的关键事件不会被监听,因为YouTube iframe是一个完全独立的窗口。为了解决这个问题,你可以在YouTube iframe上覆盖一个透明的div,并构建自己的播放/暂停按钮。这样就没有人可以点击iframe而失去父窗口的焦点。

我希望这对你有帮助!