How can I make the YouTube player scale to the width of the page but also keep the aspect ratio?

后端 未结 14 1928
一向
一向 2021-01-30 11:09

I have a YouTube video I want to put on my web page.

I want to scale the video to fit to a percent of the users browser but also to keep the aspect ratio.

I hav

14条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-30 11:35

    There are a few suggestions on the list of answers to use js to modify the structure of generated iframe. I think there is a risk with that because when you wrap the iframe inside other elements it's possible that the YouTube API will lose 'connection' with the iframe (especially if you pass the element in as a node instead of using specific id like me). It's rather to get around it actually, use javascript to modify the content before you actually trigger the youtube player.

    a snippet from my code:

    /**
     * Given the player container, we will generate a new structure like this
     *
     * 
    *
    *
    *
    * *
    *
    *
    *
    * * @return {Node} the real player node deep inside */ YouTube.renderResizable = function (playerContainer) { // clean up the content of player container playerContainer.textContent = ''; var playerDiv = document.createElement('div'); playerDiv.setAttribute('class', 'video-player'); playerContainer.appendChild(playerDiv); // add the auto-resizable-frame-div var resizeableDiv = document.createElement('div'); resizeableDiv.setAttribute('class', 'auto-resizable-iframe'); playerDiv.appendChild(resizeableDiv); // create the empty div var div = document.createElement('div'); resizeableDiv.appendChild(div); // create the real player var player = document.createElement('div'); div.appendChild(player); return player; };

提交回复
热议问题