首页 > 解决方案 > Youtube 视频作为特定部分的背景

问题描述

我需要制作一个 youtube 视频作为特定部分而不是整个页面的背景。所以我需要部分是 390px 高度和 100% 宽度。

现在我正在使用此代码,但问题是 youtube iframe 是 100% 全宽,但视频本身非常小并且带有黑色边栏。这是代码:


<div class="video-wrapper">
   <div id="player"></div>
</div>

<script>
    // 2. This code loads the IFrame Player API code asynchronously.
        var tag = document.createElement('script');

        tag.src = "https://www.youtube.com/iframe_api";
        var firstScriptTag = document.getElementsByTagName('script')[0];
        firstScriptTag.parentNode.insertBefore(tag, firstScriptTag);

        // 3. This function creates an <iframe> (and YouTube player)
        //    after the API code downloads.
        var player;
        function onYouTubeIframeAPIReady() {
            player = new YT.Player('player', {
                height: '390',
                width: '100%',
                videoId: 'EhArkyWXpO0',
                events: {
                    'onReady': onPlayerReady,
                    'onStateChange': onPlayerStateChange
                }
            });

        }


        // 4. The API will call this function when the video player is ready.
        function onPlayerReady(event) {
            event.target.playVideo();
        }

        // 5. The API calls this function when the player's state changes.
        //    The function indicates that when playing a video (state=1),
        //    the player should play for six seconds and then stop.
        var done = false;
        function onPlayerStateChange(event) {
            if (event.data == YT.PlayerState.PLAYING && !done) {
                setTimeout(stopVideo, 6000);
                done = true;
            }
        }
        function stopVideo() {
            player.stopVideo();
        }

</script>

我正在使用 youtube API 并在 javascript 中设置 100% 宽度。我很确定我必须使用 css 来实现这一点,但到目前为止还没有成功......

这是当前的输出 在此处输入图像描述

我想要的输出是没有黑色边栏的wideo

谢谢!

标签: cssyoutube

解决方案


您需要使用 javascript 通过设置width窗口或父节点的宽度来调整宽度。

将父节点的大小设置为 100% 并尝试以下操作:

node = document.getElementById("player");
player = new YT.Player('player', {
    height: node.parentNode.offsetWidth * 9 / 16,
    width: node.parentNode.offsetWidth,
    videoId: 'EhArkyWXpO0',
    events: {
        'onReady': onPlayerReady,
        'onStateChange': onPlayerStateChange
    }
)

如果要在调整窗口大小时调整大小,则必须添加一个函数window.onresize

window.onresize = function() {
    var node = document.getElementById('player');
    // fetch player; may a childnode of node[id="player"]
    player.setAttribute("width", node.parentNode.offsetWidth);
};

推荐阅读