我正在使用以下代码在我的页面上嵌入一个youtube视频:
<iframe width="400" height="300" id="newvid" src="http://www.youtube.com/embed/url?modestbranding=1&showinfo=0&feature=player_embedded&fs=0&iv_load_policy=3&rel=0" frameborder="0"></iframe>
我正在尝试使用Youtube API,因此一旦用户播放视频,将执行javascript函数,但以下代码不起作用,因为我在单击视频时没有看到任何警报显示:
<script src="https://www.youtube.com/iframe_api"></script>
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('newvid', {
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
myFunction();
}
}
}
});
}
</script>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
应该设置div容器而不是选择iFrame。(这可能无法在代码段容器中正确运行,但请在您的代码中尝试)。
<div id="newvid"></div>
<script src="https://www.youtube.com/iframe_api"></script>
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('newvid', {
height: '300',
width: '400',
videoId: 'SwxdBiazu8M', // Example video ID
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
myFunction();
}
}
}
});
}
</script>
<script>
function myFunction() {
alert("I am an alert box!");
}
</script>
下面的代码演示和执行JS function
使用enablejsapi
在iframe
-
<!doctype html>
<html>
<body>
<iframe id="ytplayer" type="text/html" width="640" height="390" src="https://www.youtube.com/embed/YtF6p_w-cSc?autoplay=1&controls=0&enablejsapi=1" frameborder="0"></iframe>
<script>
// Load 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);
// Replace the 'ytplayer' element with an <iframe> and
// YouTube player after the API code downloads.
var player;
function onYouTubePlayerAPIReady() {
player = new YT.Player('ytplayer', {
height: '390',
width: '640',
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
myFunction();
}
}
}
});
}
function myFunction() {
alert("I am an alert box!");
}
</script>
</body>
</html>
这是JSFiddle
根据上面的代码,一旦playerstate
是PLAYING
, JS function
将被调用。希望这将有助于你和你正在寻找相同的。还有,如果你有任何问题,请告诉我。
谢谢. . !