问题
I’m trying to find a way to get the keyboard to focus on the YouTube player in my page. This could, for example, make it easy to use the space bar to play/pause the video.
Here’s an example: Testing Embed Keyboard Focus (CodePen)
As it is, I’m having to click on the player for it to be able to accept keyboard shortcuts. Because this is not ideal, I’m hoping for a workaround using Javascript or jQuery to set the focus on the video.
I’m aware that – as an alternative – I could use the spacebar key to call the player object's playVideo
or pauseVideo
methods, but that still wouldn’t get me access to the full list of the YouTube player’s keyboard controls.
And if this is simply impossible, I’ll understand. But it will be nice to know. Thanks!
回答1:
In order to achieve this you would have to focus()
document embedded in the Youtube's iframe
. This is restricted by Same-origin policy for security reasons.
Here's a piece of code for completeness
function onPlayerReady(event) {
document.querySelector('#player').contentDocument.body.focus();
}
And it would throw
Uncaught SecurityError: Failed to read the 'contentDocument' property from 'HTMLIFrameElement':
回答2:
You can do something like this to implement whatever hotkeys you want to enable for the player at any rate.
http://codepen.io/anon/pen/jbgeYo
Basically you create an input (can style it so that it blends in, you can't do display:none as that won't let you assign focus), and then attach a keypress event to that input. You then can call functions on the "player" API object which allows you to play/pause etc.
var dummy=document.getElementById("dummyFocus");
dummy.focus();
dummy.addEventListener("keypress",function(event){
if(event.keyCode== 32){
if(player.getPlayerState() == 1){
player.pauseVideo();
}
else{
player.playVideo();
}
}
});
Insert that after you create your player object, and add an input (I used type="button") to the page with id="dummyFocus"
Edit as needed, but that's a workaround anyway.
来源:https://stackoverflow.com/questions/33899401/setting-keyboard-focus-to-youtube-embed