gpt4 book ai didi

javascript - YouTube 播放器 iframe 的非动态插入不会触发事件

转载 作者:行者123 更新时间:2023-11-28 00:42:43 30 4
gpt4 key购买 nike

我正在使用 youtube 的 iframe api

https://developers.google.com/youtube/iframe_api_reference#Loading_a_Video_Player

我想写<iframe>手动标记(不是异步插入)。文档表明这是可能的

If you do write the tag, then when you construct the YT.Player object, you do not need to specify values for the width and height, which are specified as attributes of the tag(...)

但是当我插入<iframe>时直接标记

  <iframe id="player" type="text/html" width="640" height="390"
src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com"
frameborder="0"></iframe>

并删除动态标记生成

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

(以及创建新播放器实例时选项中的宽度、高度和 ID)

我无法调用 onYouTubeIframeAPIReady 函数。我尝试过使用脚本标记的动态插入并且它有效。该文档对于不动态插入时需要什么有点不清楚 - 所以我将不胜感激的建议

谢谢

最佳答案

当页面上已存在 iframe 元素时,您仍然需要加载 iframe javascript 库,因为正是该库调用 onYouTubeIFrameAPIReady。所以你的代码应该是这样的:

<iframe id="player" type="text/html" width="640" height="390"
src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com"
frameborder="0"></iframe>

<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 player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('player', {
events: {
'onReady': onPlayerReady,
'onStateChange': onPlayerStateChange
}
});
}
</script>

请注意,在这种情况下,您传递给 onYouTubeIFrameAPIReady 的值是 iframe 的 ID,而不是 div 的 ID ...库会识别出这是一个 iframe 并 Hook 现有视频,而不是尝试为您动态生成 iframe。

关于javascript - YouTube 播放器 iframe 的非动态插入不会触发事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27761233/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com