javascript - YouTube API 以 5 x 3 网格而不是单列列表列出播放列表图标

标签 javascript jquery html css youtube-api

下面是我的代码...Javascript 和 JQuery 位于头部,但 CSS 是外部文档。

有一个带有存储名称的 cookie 的额外片段...忽略它...

它是 YouTube API,用于提取我最近上传的内容。一切都很好,除了我最终在一列中得到了 15 个视频播放列表,而且我一直无法弄清楚如何让它排序为任何类型的网格排列(5 x 3 或其他)。播放列表中加载的视频数量可以调整为 5x3、4x3,任何 x 都可以。

实时查看此页面的位置:98.255.116.178

有什么想法或指导可以将这些视频排列成网格吗?

<!DOCTYPE HTML>
<html>
    <head>
        <title>My Sandbox</title>
        <link rel="stylesheet" type="text/css" href="CSS/Style.CSS">
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js">
        </script>   
        <script>
            jQuery(function($){
              $("#video-container").on('click', '.video_select', function(e){
                console.log(e);
                var buttonSource = $(this).data('video');
                var embededVideo = $('#youTube_video');
                    embededVideo.attr('src', buttonSource);
                    return false;
              });
            });


            function getCookie(c_name)
                {
                var c_value = document.cookie;
                var c_start = c_value.indexOf(" " + c_name + "=");
                    if (c_start == -1){
                        c_start = c_value.indexOf(c_name + "=");
                    }
                    if (c_start == -1){
                        c_value = null;
                    }
                    else{
                        c_start = c_value.indexOf("=", c_start) + 1;
                var c_end = c_value.indexOf(";", c_start);
                    if (c_end == -1){
                        c_end = c_value.length;
                    }
                        c_value = unescape(c_value.substring(c_start,c_end));
                    }
                    return c_value;
                    }

            function setCookie(c_name,value,exdays){
                var exdate=new Date();
                    exdate.setDate(exdate.getDate() + exdays);
                var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
                    document.cookie=c_name + "=" + c_value;
                    }

            function checkCookie(){
                var username=getCookie("username");
                    if (username!=null && username!=""){
                        alert("Welcome back " + username);
                        document.getElementById("title_script").innerHTML="Welcome "+username+" to my sandbox";
                        }
                    else{
                        username=prompt("Please enter your name:","");
                        if (username!=null && username!=""){
                        setCookie("username",username,365);
                        document.getElementById("title_script").innerHTML="Welcome "+username+" to my sandbox";
                        }
                    }
            }





                </script>



                  <script>
        //This is the Authorization by Client ID http://d.pr/i/mEmY
        // The client id is obtained from the Google APIs Console at https://code.google.com/apis/console
        // If you run access this code from a server other than http://localhost, you need to register
        // your own client id.
        var OAUTH2_CLIENT_ID = '367567738093.apps.googleusercontent.com';
        var OAUTH2_SCOPES = [
          'https://www.googleapis.com/auth/youtube'
        ];

        // This callback is invoked by the Google APIs JS client automatically when it is loaded.
        googleApiClientReady = function() {
          gapi.auth.init(function() {
            window.setTimeout(checkAuth, 1);
          });
        }

        // Attempt the immediate OAuth 2 client flow as soon as the page is loaded.
        // If the currently logged in Google Account has previously authorized OAUTH2_CLIENT_ID, then
        // it will succeed with no user intervention. Otherwise, it will fail and the user interface
        // to prompt for authorization needs to be displayed.
        function checkAuth() {
          gapi.auth.authorize({
            client_id: OAUTH2_CLIENT_ID,
            scope: OAUTH2_SCOPES,
            immediate: true
          }, handleAuthResult);
        }

        // Handles the result of a gapi.auth.authorize() call.
        function handleAuthResult(authResult) {
          if (authResult) {
            // Auth was successful; hide the things related to prompting for auth and show the things
            // that should be visible after auth succeeds.
            $('.pre-auth').hide();
            loadAPIClientInterfaces();
          } else {
            // Make the #login-link clickable, and attempt a non-immediate OAuth 2 client flow.
            // The current function will be called when that flow is complete.
            $('#login-link').click(function() {
              gapi.auth.authorize({
                client_id: OAUTH2_CLIENT_ID,
                scope: OAUTH2_SCOPES,
                immediate: false
                }, handleAuthResult);
            });
          }
        }

        // Loads the client interface for the YouTube Analytics and Data APIs.
        // This is required before using the Google APIs JS client; more info is available at
        // http://code.google.com/p/google-api-javascript-client/wiki/GettingStarted#Loading_the_Client
        function loadAPIClientInterfaces() {
          gapi.client.load('youtube', 'v3', function() {
            handleAPILoaded();
          });
        }



      //This is the uploads script
      // Some variables to remember state.
      var playlistId, nextPageToken, prevPageToken;

      // Once the api loads call a function to get the uploads playlist id.
      function handleAPILoaded() {
        requestUserUploadsPlaylistId();
      }

      //Retrieve the uploads playlist id.
      function requestUserUploadsPlaylistId() {
        // https://developers.google.com/youtube/v3/docs/channels/list
        var request = gapi.client.youtube.channels.list({
          // mine: '' indicates that we want to retrieve the channel for the authenticated user.
          // mine: false,
          id: 'UCziks4y-RixDhWljY_es-tA',
          part: 'contentDetails'
        });
        request.execute(function(response) {
          console.log(response);
          playlistId = response.result.items[0].contentDetails.relatedPlaylists.uploads;
          requestVideoPlaylist(playlistId);
        });
      }

      // Retrieve a playist of videos.
      function requestVideoPlaylist(playlistId, pageToken) {
        $('#video-container').html('');
        var requestOptions = {
          playlistId: playlistId,
          part: 'snippet',
          maxResults: 15
        };
        if (pageToken) {
          requestOptions.pageToken = pageToken;
        }
        var request = gapi.client.youtube.playlistItems.list(requestOptions);
        request.execute(function(response) {
          // Only show the page buttons if there's a next or previous page.
          console.log (response);
          nextPageToken = response.result.nextPageToken;
          var nextVis = nextPageToken ? 'visible' : 'hidden';
          $('#next-button').css('visibility', nextVis);
          prevPageToken = response.result.prevPageToken
          var prevVis = prevPageToken ? 'visible' : 'hidden';
          $('#prev-button').css('visibility', prevVis);

          var playlistItems = response.result.items;
          if (playlistItems) {
            // For each result lets show a thumbnail.
            jQuery.each(playlistItems, function(index, item) {
              createDisplayThumbnail(item.snippet);
            });
          } else {
            $('#video-container').html('Sorry you have no uploaded videos');
          }
        });
      }


      // Create a thumbnail for a video snippet.
      function createDisplayThumbnail(videoSnippet) {
        console.log(videoSnippet);
        var titleEl = $('<h3>');
        titleEl.addClass('video-title');
        $(titleEl).html(videoSnippet.title);
        var thumbnailUrl = videoSnippet.thumbnails.medium.url;
        var videoLink=$('<a>');
        videoLink.attr('data-video','http://www.youtube.com/embed/'+videoSnippet.resourceId.videoId+'?autoplay=1');
        videoLink.append(div)
        videoLink.addClass('video_select')

        var div = $('<div>');
        div.addClass('video-content');
        div.css('backgroundImage', 'url("' + thumbnailUrl + '")');
        div.append(titleEl);
        videoLink.append(div)
        $('#video-container').append(videoLink);

      }

      // Retrieve the next page of videos.
      function nextPage() {
        requestVideoPlaylist(playlistId, nextPageToken);
      }

      // Retrieve the previous page of videos.
      function previousPage() {
        requestVideoPlaylist(playlistId, prevPageToken);
      }
    </script>
















































    </head>
<body onload="checkCookie()" class="background_color">
<div class="wrap">
  <h1 id="title_script">Welcome to my Sandbox</h1>
</div>
<div class="wrap">
    <iframe id='youTube_video' width="853" height="480" src="//www.youtube.com/embed/io78hmjAWHw?autoplay=1" frameborder="0" allowfullscreen></iframe>
</div>

<div id="login-container" class="pre-auth">Please click <a href="#" id="login-link">authorize</a> to continue.
</div>
<div id="video-container">
</div>
<div class="button-container">
  <button id="prev-button" class="paging-button" onclick="previousPage();">Previous Page</button>
  <button id="next-button" class="paging-button" onclick="nextPage();">Next Page</button>
</div>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>














</body>
</html>

当然还有 CSS:

.wrap{
    width: 1000px;
    margin: auto;
    text-align: center;
    }
.background_color{
    background-color: #AABF94;
    }   
h1{
    }





.paging-button {
visibility: hidden;
}

.video-content {
width: 200px;
height: 200px;
background-position: center;
background-repeat: no-repeat;
float: left;
position: relative;
margin: 5px;
}

.video-title {
width: 100%;
text-align: center;
background-color: rgba(0, 0, 0, .5);
color: white;
top: 50%;
left: 50%;
position: absolute;
-moz-transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}

.video-content:nth-child(3n+1) {
clear: both;
}

.button-container {
clear: both;
}

最佳答案

这似乎对我有用。

您的代码更改为:

(如果不是您的,请不要忘记更改代码行:var OAUTH2_CLIENT_ID = 'your-id';)

<!DOCTYPE HTML>
<html>
    <head>
        <title>My Sandbox</title>
        <link rel="stylesheet" type="text/css" href="CSS/Style.CSS">
        <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.10.2.min.js">
        </script>   
        <script>
            jQuery(function($){
              $("#video-container").on('click', '.video_select', function(e){
                console.log(e);
                var buttonSource = $(this).data('video');
                var embededVideo = $('#youTube_video');
                    embededVideo.attr('src', buttonSource);
                    return false;
              });
            });


            function getCookie(c_name)
                {
                var c_value = document.cookie;
                var c_start = c_value.indexOf(" " + c_name + "=");
                    if (c_start == -1){
                        c_start = c_value.indexOf(c_name + "=");
                    }
                    if (c_start == -1){
                        c_value = null;
                    }
                    else{
                        c_start = c_value.indexOf("=", c_start) + 1;
                var c_end = c_value.indexOf(";", c_start);
                    if (c_end == -1){
                        c_end = c_value.length;
                    }
                        c_value = unescape(c_value.substring(c_start,c_end));
                    }
                    return c_value;
                    }

            function setCookie(c_name,value,exdays){
                var exdate=new Date();
                    exdate.setDate(exdate.getDate() + exdays);
                var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
                    document.cookie=c_name + "=" + c_value;
                    }

            function checkCookie(){
                var username=getCookie("username");
                    if (username!=null && username!=""){
                        alert("Welcome back " + username);
                        document.getElementById("title_script").innerHTML="Welcome "+username+" to my sandbox";
                        }
                    else{
                        username=prompt("Please enter your name:","");
                        if (username!=null && username!=""){
                        setCookie("username",username,365);
                        document.getElementById("title_script").innerHTML="Welcome "+username+" to my sandbox";
                        }
                    }
            }

                </script>



                  <script>
        //This is the Authorization by Client ID http://d.pr/i/mEmY
        // The client id is obtained from the Google APIs Console at https://code.google.com/apis/console
        // If you run access this code from a server other than http://localhost, you need to register
        // your own client id.
        var OAUTH2_CLIENT_ID = '367567738093.apps.googleusercontent.com';
        var OAUTH2_SCOPES = [
          'https://www.googleapis.com/auth/youtube'
        ];

        // This callback is invoked by the Google APIs JS client automatically when it is loaded.
        googleApiClientReady = function() {
          gapi.auth.init(function() {
            window.setTimeout(checkAuth, 1);
          });
        }

        // Attempt the immediate OAuth 2 client flow as soon as the page is loaded.
        // If the currently logged in Google Account has previously authorized OAUTH2_CLIENT_ID, then
        // it will succeed with no user intervention. Otherwise, it will fail and the user interface
        // to prompt for authorization needs to be displayed.
        function checkAuth() {
          gapi.auth.authorize({
            client_id: OAUTH2_CLIENT_ID,
            scope: OAUTH2_SCOPES,
            immediate: true
          }, handleAuthResult);
        }

        // Handles the result of a gapi.auth.authorize() call.
        function handleAuthResult(authResult) {
          if (authResult) {
            // Auth was successful; hide the things related to prompting for auth and show the things
            // that should be visible after auth succeeds.
            $('.pre-auth').hide();
            loadAPIClientInterfaces();
          } else {
            // Make the #login-link clickable, and attempt a non-immediate OAuth 2 client flow.
            // The current function will be called when that flow is complete.
            $('#login-link').click(function() {
              gapi.auth.authorize({
                client_id: OAUTH2_CLIENT_ID,
                scope: OAUTH2_SCOPES,
                immediate: false
                }, handleAuthResult);
            });
          }
        }

        // Loads the client interface for the YouTube Analytics and Data APIs.
        // This is required before using the Google APIs JS client; more info is available at
        // http://code.google.com/p/google-api-javascript-client/wiki/GettingStarted#Loading_the_Client
        function loadAPIClientInterfaces() {
          gapi.client.load('youtube', 'v3', function() {
            handleAPILoaded();
          });
        }



      //This is the uploads script
      // Some variables to remember state.
      var playlistId, nextPageToken, prevPageToken;

      // Once the api loads call a function to get the uploads playlist id.
      function handleAPILoaded() {
        requestUserUploadsPlaylistId();
      }

      //Retrieve the uploads playlist id.
      function requestUserUploadsPlaylistId() {
        // https://developers.google.com/youtube/v3/docs/channels/list
        var request = gapi.client.youtube.channels.list({
          // mine: '' indicates that we want to retrieve the channel for the authenticated user.
          // mine: false,
          id: 'UCziks4y-RixDhWljY_es-tA',
          part: 'contentDetails'
        });
        request.execute(function(response) {
          console.log(response);
          playlistId = response.result.items[0].contentDetails.relatedPlaylists.uploads;
          requestVideoPlaylist(playlistId);
        });
      }

      // Retrieve a playist of videos.
      function requestVideoPlaylist(playlistId, pageToken) {
        $('#video-container').html('');
        var requestOptions = {
          playlistId: playlistId,
          part: 'snippet',
          maxResults: 15
        };
        if (pageToken) {
          requestOptions.pageToken = pageToken;
        }
        var request = gapi.client.youtube.playlistItems.list(requestOptions);
        request.execute(function(response) {
          // Only show the page buttons if there's a next or previous page.
          console.log (response);
          nextPageToken = response.result.nextPageToken;
          var nextVis = nextPageToken ? 'visible' : 'hidden';
          $('#next-button').css('visibility', nextVis);
          prevPageToken = response.result.prevPageToken
          var prevVis = prevPageToken ? 'visible' : 'hidden';
          $('#prev-button').css('visibility', prevVis);

          var playlistItems = response.result.items;
          if (playlistItems) {
            // For each result lets show a thumbnail.
            jQuery.each(playlistItems, function(index, item) {
              createDisplayThumbnail(item.snippet);
            });
          } else {
            $('#video-container').html('Sorry you have no uploaded videos');
          }
        });
      }


      // Create a thumbnail for a video snippet.
      function createDisplayThumbnail(videoSnippet) {
        console.log(videoSnippet);
        var titleEl = $('<h3>');
        titleEl.addClass('video-title');
        $(titleEl).html(videoSnippet.title);
        var thumbnailUrl = videoSnippet.thumbnails.medium.url;
        var videoLink=$('<a>');
        videoLink.attr('data-video','http://www.youtube.com/embed/'+videoSnippet.resourceId.videoId+'?autoplay=1');
        videoLink.append(div)
        videoLink.addClass('video_select')

        var div = $('<div>');
        div.addClass('video-content');
        div.css('backgroundImage', 'url("' + thumbnailUrl + '")');
        div.append(titleEl);
        videoLink.append(div)
        $('#video-container').append(videoLink);

      }

      // Retrieve the next page of videos.
      function nextPage() {
        requestVideoPlaylist(playlistId, nextPageToken);
      }

      // Retrieve the previous page of videos.
      function previousPage() {
        requestVideoPlaylist(playlistId, prevPageToken);
      }
    </script>


    </head>
<body onload="checkCookie()" class="background_color">
<div class="wrap">
  <h1 id="title_script">Welcome to my Sandbox</h1>
</div>
<div class="wrap">
    <iframe id='youTube_video' width="853" height="480" src="//www.youtube.com/embed/io78hmjAWHw?autoplay=1" frameborder="0" allowfullscreen></iframe>
</div>

<div id="login-container" class="pre-auth">Please click <a href="#" id="login-link">authorize</a> to continue.
</div>
<div id="video-container" class="box_wrapper">
</div>
<div class="button-container">
  <button id="prev-button" class="paging-button" onclick="previousPage();">Previous Page</button>
  <button id="next-button" class="paging-button" onclick="nextPage();">Next Page</button>
</div>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>

</body>
</html>

你的 CSS 变成了:

.wrap{
    width: 1000px;
    margin: auto;
    text-align: center;
    }
.background_color{
    background-color: #AABF94;
    }   
h1{
    }

.paging-button {
visibility: hidden;
}

.box_wrapper {
    margin: 0;
    height: 100%;
    width: 1000px;
    overflow: hidden;
}

.video_select {
float: left;
display: table-cell;
}

.video-content {
width: 200px;
height: 200px;
background-position: center;
background-repeat: no-repeat;
float: left;
position: relative;
margin: 5px;
display: table-cell;
}

.video-title {
width: 100%;
text-align: center;
background-color: rgba(0, 0, 0, .5);
color: white;
top: 50%;
left: 50%;
position: absolute;
-moz-transform: translate(-50%, -50%);
-webkit-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
}

.video-content:nth-child(3n+1) {
clear: both;
}

.button-container {
clear: both;
}

关于javascript - YouTube API 以 5 x 3 网格而不是单列列表列出播放列表图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18692107/

相关文章:

javascript - knockout JS : Stop a particular property from setting dirty flag

php - 通过 url 将 javascript var 传递给 PHP

javascript - 带缩略图的 Bootstrap 轮播(多个轮播)

javascript - 使用 JavaScript 读取 div 的宽度

javascript - 单击同一 Div 时打开弹出窗口,弹出窗口关闭后

jquery - 使用 jQuery 将类添加到列中的下一个表格单元格

javascript - 我如何使用 jquery 创建覆盖联系表单

javascript - 如何使用 jquery 删除 html select 具有重复的数据和文本名称?

javascript - 如何在页面加载时加载此 jquery 通知栏而不是单击按钮?

javascript - 将变量的内容附加到 html 内的文本文件