Я пытаюсь создать веб-страницу (с Laravel), которая при нажатии кнопки открывает «iframe» YouTube в полноэкранном режиме и воспроизводит его с помощью API YouTube (https://developers.google.com/youtube/iframe_api_reference* 1003). *)
Когда я делаю это только с 1 кнопкой и 1 игроком, он прекрасно работает, как показано в следующем коде.
<h1>One-click play+fullscreen via YouTube API</h1>
Suggested code from this <a href="http://stackoverflow.com/a/20289540/288906">StackOverflow answer</a>
<h2>Instructions</h2>
<ol>
<li>Click on [play fullscreen]</li>
<li>Click on the fullscreen button in youtube's player to exit fullscreen</li>
</ol>
<script async src="https://www.youtube.com/iframe_api"></script>
<button>play fullscreen</button>
<div id="player" ></div>
<script>
var player, iframe;
var $ = document.querySelector.bind(document);
console.log($('#player'));
// init player
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
height: '200',
width: '300',
videoId: 'Sq3wR__guNA',
events: {
'onReady': onPlayerReady
}
});
}
iframes=[];
// when ready, wait for clicks
function onPlayerReady(event) {
iframes[0] = $('#player')
setupListener();
}
function setupListener (){
$('button').addEventListener('click', playFullscreen);
}
function playFullscreen (){
player.playVideo();//won't work on mobile
console.log(player);
var requestFullScreen = iframes[0].requestFullScreen || iframes[0].mozRequestFullScreen || iframes[0].webkitRequestFullScreen;
if (requestFullScreen) {
console.log(iframes[0]);
requestFullScreen.bind(iframes[0])();
}
}
</script>
Проблема возникает, когда я пытаюсь открыть кнопку 1 открытой player1 button2 открыть player2 и т. д.
Вот код HTML, который я использую, важно отметить, что данные, отправленные с «data-», правильно достигают файла javascript:
<div class="limiter">
<div class="container-table100">
<div class="wrap-table100">
<div class="table100">
<table>
<thead>
<tr class="table100-head">
<th class="column1">To</th>
<th class="column2">Map</th>
<th class="column3">Description</th>
<th class="column4">Times voted</th>
<th class="column5">Times favorited</th>
<th class="column6">Rating</th>
<th class="column7">Video</th>
</tr>
</thead>
<tbody>
<?php $totalVideos = 12;?>
<script type="text/javascript">var totalVideos = <?php echo $totalVideos;?>;</script>
@foreach($plays as $play)
<!--Si es que se llego al video 12, dejan de crearse filas-->
@if ($loop->iteration > $totalVideos)
@break
@endif
<tr>
<td class="column1">{{$play->to}}</td>
<td class="column2">{{$play->map}}</td>
<td class="column3">{{$play->description}}</td>
<td class="column4">{{$play->timesvoted}}</td>
<td class="column5">{{$play->timesfavorited}}</td>
<td class="column6">{{$play->rating}}</td>
<td class="column7">
<button id="button{{$loop->iteration}}">play fullscreen</button>
<div id="player{{$loop->iteration}}" class="youtube-video" data-playId='{{$play->id}}' data-videoId='{{$play->videoId}}' data-startTime='{{$play->startTime}}' data-endTime='{{$play->endTime}}'></div>
</td>
</tr>
@endforeach
</tbody>
</table>
</div>
</div>
</div>
</div>
<script async src="https://www.youtube.com/iframe_api"></script>
<!-- Youtube plugin test -->
<script src="{{ asset('js/video-popup.js') }}" defer></script>
Вот код javascript:
var data = document.getElementsByClassName('youtube-video');
requestFullScreen();
function requestFullScreen() {
if (document.fullscreenEnabled) {
console.log("Your browser can use fullscreen right now");
} else {
console.log('Your browser cannot use fullscreen right now');
}
}
var playerConfigList=[];
for (var i = 0; i < data.length; i++) {
var videoId = data[i].attributes[3].nodeValue;
var startSeconds = data[i].attributes[4].nodeValue; // set your own video start time when loop play
var endSeconds = data[i].attributes[5].nodeValue; // set your own video end time when loop play
playerConfigList[i] = ({
height: '300',
width: '300',
videoId: videoId,
playerVars: {
autoplay: 0, // Auto-play the video on load
controls: 2, // Show pause/play buttons in player
showinfo: 0, // Hide the video title
modestbranding: 1, // Hide the Youtube Logo
fs: 1, // Hide the full screen button
cc_load_policy: 0, // Hide closed captions
iv_load_policy: 3, // Hide the Video Annotations
start: startSeconds,
end: endSeconds,
autohide: 0, // Hide video controls when playing
},
events: {
'onReady': onPlayerReady,
'onStateChange': onStateChange // reference to Iframe API
//onReady: function(e) { // mute the video when loaded
//e.target.mute();
//}
}
});
}
var player = [];
// init player
function onYouTubeIframeAPIReady() {
for(i = 0; i < data.length; i++){
player[i] = new YT.Player('player'+(i+1), playerConfigList[i]);
}
}
var iframes=[];
function onPlayerReady(event){
for(i = 0; i < data.length; i++){
if((data[i].attributes[0].nodeValue).localeCompare('player'+(event.target.f.dataset.playid)) == 0)
{
iframes[i] = data[i];
setupListener(event);
}
}
}
var allButtons = document.querySelectorAll('button');
function setupListener (event){
for(i = 0; i < allButtons.length; i++){
if((data[i].attributes[0].nodeValue).localeCompare('player'+(event.target.f.dataset.playid)) == 0)
{
allButtons[event.target.f.dataset.playid].addEventListener('click', playFullscreen(event));
}
}
}
var reqFullScreenArray=[];
function playFullscreen (event){
for(i = 0; i < data.length; i++){
if((data[i].attributes[0].nodeValue).localeCompare('player'+(event.target.f.dataset.playid)) == 0)
{
player[event.target.f.dataset.playid-1].playVideo(); //won't work on mobile
console.log(player[event.target.f.dataset.playid-1]);
reqFullScreenArray[event.target.f.dataset.playid-1] = iframes[event.target.f.dataset.playid-1].requestFullScreen || iframes[event.target.f.dataset.playid-1].mozRequestFullScreen || iframes[event.target.f.dataset.playid-1].webkitRequestFullScreen;
if(reqFullScreenArray[event.target.f.dataset.playid-1]) {
reqFullScreenArray[event.target.f.dataset.playid-1].bind(iframes[event.target.f.dataset.playid-1])();
}
}
}
}
function onStateChange(state) {
if (state.data === YT.PlayerState.ENDED)
{
for(i = 0; i < data.length; i++)
{
if(state['target'].f.attributes[0].nodeValue.localeCompare(player[i].f.id) == 0)
{
player[i].loadVideoById({
videoId: playerConfigList[i].videoId,
startSeconds: playerConfigList[i].playerVars.start,
endSeconds: playerConfigList[i].playerVars.end
});
}
}
}
}
Может кто-нибудь помочь мне исправить мой код или найти другое решение, правда в том, что я только учусь javascript, и у меня есть укоренилось все. Заранее большое спасибо.