Youtube:在一个页面中添加两个嵌入的视频

时间:2014-02-05 12:59:09

标签: javascript youtube youtube-api

这比JavaScript API更像是一个JavaScript问题。我复制并修改了YouTube iFrame API,以便同时添加两个视频。第一个自动播放,第二个不播放。

我面临的问题是它只显示第二个视频。

这是我到目前为止所做的:

    <script>
    var tag = document.createElement('script');

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

    var player1;

    function onYouTubeIframeAPIReady() {
        player1 = new YT.Player('player1', {
            height: '315',
            width: '420',
            videoId: 'bHQqvYy5KYo',
            events: {
                'onReady': onPlayerReady
            }
        });
    }

    var player2;

    function onYouTubeIframeAPIReady() {
        player2 = new YT.Player('player2', {
            height: '315',
            width: '420',
            videoId: 'M3uWx-fhjUc',
            events: {
                'onReady': stopVideo
            }
        });
    }

    function onPlayerReady(event) {
        event.target.playVideo();
    }

    function stopVideo() {
        player.stopVideo();
    }
</script>


<div id="player1"></div>
<br>
<div id="player2"></div>

答案后的固定代码:

    <script>
    var tag = document.createElement('script');

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

    var player1;
    var player2;

    function onYouTubeIframeAPIReady() {
        player1 = new YT.Player('player1', {
            height: '315',
            width: '420',
            videoId: 'bHQqvYy5KYo',
            events: {
                'onReady': onPlayerReady
            }
        });

        player2 = new YT.Player('player2', {
            height: '315',
            width: '420',
            videoId: 'M3uWx-fhjUc',
            events: {
                'onReady': stopVideo
            }
        });
    }


    function onPlayerReady(event) {
        event.target.playVideo();
    }

    function stopVideo() {
        player.stopVideo();
    }
</script>


<div id="player1"></div>
<br>
<div id="player2"></div>

1 个答案:

答案 0 :(得分:1)

您有两个名为onYouTubeIframeAPIReady的函数。首先将代码合并到一个函数中。