2

所以下面是我的代码...... 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;
}
4

2 回答 2

2

这似乎对我有用。

您的代码更改为:

(如果不是你的,不要忘记更改代码行: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;
}
于 2013-09-10T21:04:17.457 回答
0

这与修复无关,但我稍微清理了 HTML:

<div class="wrap">
  <h1 id="title_script">Welcome to my Sandbox</h1>
  <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>
</div>
<script src="https://apis.google.com/js/client.js?onload=googleApiClientReady"></script>

在 CSS 中,将 wrap 从宽度 1000 更改为 1060 并添加以下两行:

#video-container a {
    float: left;
}
#video-container{
    width: 100%;
}

像魅力一样工作:屏幕截图

于 2013-09-10T21:55:38.237 回答