可以添加一个onclick事件到YouTube iframe? [英] Possible to add an onclick event to a YouTube iframe?
问题描述
我有一个带有HTML5音频播放器的网站,并嵌入了YouTube音乐视频。我想这样做是为了当用户点击YouTube视频播放音乐时,音乐将停止播放。包装iframe在
< div id ='vidWrapper'onclick ='pauseAudio()'> YT stuff< / div> code>
适用于iframe之外的像素条,但不是当您点击实际视频时。任何人有任何想法?
您应该使用 YouTube IFrame API 。为玩家状态改变时添加一个 onStateChange
的事件监听器来获得通知。请参阅下面的示例代码。
<!DOCTYPE html>
< html>
< head>
< script src =https://www.youtube.com/iframe_api>< / script>
< / head>
< body>
< div id ='vidWrapper'>
<! - < iframe> (和视频播放器)将取代这个< div>标签。 - >
< div id =ytplayer>< / div>
< / div>
< script>
var player;
function onYouTubeIframeAPIReady(){
player = new YT.Player('ytplayer',{
height:'390',
width:'640',
videoId:'M7lc1UVf-VE',
events:{$ b $'onStateChange':function(event){
if(event.data == YT.PlayerState.PLAYING){
pauseAudio();
}
}
}
});
}
函数pauseAudio(){
...
}
< / script>
< / body>
< / html>
I've got a site with an HTML5 audio player and embedded YouTube music videos. I'd like to make it so that when the user clicks on a YouTube video to play it the music will stop. Wrapping the iframe in
<div id='vidWrapper' onclick='pauseAudio()'>YT stuff</div>
works for the sliver of pixels outside of the iframe, but not when you click on the actual video. Anyone have any ideas?
You should use the YouTube IFrame API. Add an event listener for onStateChange
to get notified when the player's state changes. See the sample code below.
<!DOCTYPE html>
<html>
<head>
<script src="https://www.youtube.com/iframe_api"></script>
</head>
<body>
<div id='vidWrapper'>
<!-- The <iframe> (and video player) will replace this <div> tag. -->
<div id="ytplayer"></div>
</div>
<script>
var player;
function onYouTubeIframeAPIReady() {
player = new YT.Player('ytplayer', {
height: '390',
width: '640',
videoId: 'M7lc1UVf-VE',
events: {
'onStateChange': function(event) {
if (event.data == YT.PlayerState.PLAYING) {
pauseAudio();
}
}
}
});
}
function pauseAudio() {
...
}
</script>
</body>
</html>
这篇关于可以添加一个onclick事件到YouTube iframe?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!