播放YouTube影片时如何在iframe上添加按键事件?

时间:2018-10-21 08:34:34

标签: javascript html video iframe

我无法将<video>标签用于youtube视频,因此我将youtube嵌入<iframe>内以播放youtube视频:

<iframe type="text/html" 
    width="640" 
    height="385" 
    src="http://www.youtube.com/embed/VIDEO_ID"
    frameborder="0">
</iframe>

播放视频效果很好。但是我需要支持按escape键才能停止播放视频。以下代码适用于<video>标签,但播放视频时不适用于iframe。该视频似乎在播放时需要键盘控制。有什么方法可以让我聆听youtube iframe的键盘事件吗?

window.addEventListener('keydown',(e) => {
    if (e.key === 'Escape') {
         ...
    }
});

我尝试通过youtube api iframe播放视频,但是在播放视频时不会触发keydown事件。可以找到此代码:https://codepen.io/zhaoyi0113/pen/YJvJay。如果视频获得焦点并正在播放,则不会触发事件侦听器。

2 个答案:

答案 0 :(得分:0)

这是使用The youtube api iframe添加youtube视频的iframe的正确方法,请检查此代码,希望对您有帮助(该视频将无法运行,请复制代码并在浏览器中运行):

<!DOCTYPE html>
<html>

<body>

<div id="player"></div>

<script>

// This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;

function onYouTubeIframeAPIReady() {
	player = new YT.Player('player', {
		height: '360',
		width: '640',
		videoId: 'M7lc1UVf-VE',
		events: {
			'onReady': onPlayerReady,
			'onStateChange': onPlayerStateChange
		}
	});
}

// The API will call this function when the video player is ready.
function onPlayerReady(event) {
	event.target.playVideo();
}

// 	  The API calls this function when the player's state changes.
//    The function indicates that when playing a video (state=1),
//    the player should play for six seconds and then stop.
var done = false;

function onPlayerStateChange(event) {
	if (event.data == YT.PlayerState.PLAYING && !done) {
		setTimeout(stopVideo, 6000);
		done = true;
	}
}

// Stop video
function stopVideo() {
	player.stopVideo();
}

// Your event listener on keydown
document.addEventListener('keydown',(e) => {
	alert("video will be stoped !!");
    if (e.key === 'Escape') {
         stopVideo()
    }
}, false);

</script>
</body>

</html>

答案 1 :(得分:0)

您将必须使用YouTube的IFrame Player API来实现所需的功能。 该代码将注入所需的api,在页面上创建iframe并加载您提供的ID的视频:

HTML

<!-- The <iframe> (and video player) will replace this <div> tag. -->
<div id="player"></div>

JavaScript

// 1. This code loads the IFrame Player API code asynchronously.
var tag = document.createElement('script');

tag.src = "https://www.youtube.com/iframe_api";
var firstScriptTag = document.getElementsByTagName('script')[0];
firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

// 2. This function creates an <iframe> (and YouTube player)
//    after the API code downloads.
var player;
function onYouTubeIframeAPIReady() {
    player = new YT.Player('player', {
        height: '390',
        width: '640',
        videoId: 'M7lc1UVf-VE',
        events: {
            'onReady': onPlayerReady
        }
    });
}

// The API will call this function when the video player is ready.
function onPlayerReady(event) {
    event.target.playVideo();
}
// Pause the video
function pauseVideo() {
    player.pauseVideo();
}
// your existing code
window.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
        pauseVideo();
    }
});

有关详细信息,请使用其API Reference

YouTube播放器不允许自定义键盘快捷键,并且在聚焦视频时您无法收听浏览器事件。顺便说一句,您可以使用空格键播放/暂停视频。