YouTube:在一页中添加两个嵌入式视频



这比youtube 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>

您有两个名为 onYouTubeIframeAPIReady的功能。首先在单个功能中合并代码。

相关内容

  • 没有找到相关文章

最新更新