使用HTML5我在页面上有2个音频元素和1个视频元素。 很简单,我想添加JavaScript功能,以防止它们同时播放。 我的主要问题是如何定位默认播放器的点击事件。 HTML在下面,谢谢;
<section id="mp3Section">
<h2>MUSIC</h2>
<ul>
<li>Lovers Pass<audio id="audioLP" controls="controls" preload="auto" autobuffer>
<p class="redText">Sorry. Your browser does not support this audio element</p>
<source src="music/loversPass.mp3" />
<source src="music/loversPass.wav" />
</audio></li>
<li>All The Fun<audio id="audioATF" controls="controls" preload="auto" autobuffer="autobuffer">
<p class="redText">Sorry. Your browser does not support this audio element</p>
<source src="music/allTheFun.mp3" />
<source src="music/allTheFun.wav" />
</audio></li>
</ul>
</section>
<section id="videoSection">
<h2>Video</h2>
<video id="vidScreen" controls poster="images/vidThumb.jpg">
<source src="videos/loversPassOGV.ogg"/>
<source src="videos/loversPassVid.mp4" />
</video>
</section>
答案 0 :(得分:5)
我是怎么做的(为了简单起见使用jQuery,虽然不是必需的):
$('audio,video').bind('play', function() {
activated = this;
$('audio,video').each(function() {
if(this != activated) this.pause();
});
});
答案 1 :(得分:1)
audio
和video
元素包含您可以捕获的事件。请参阅示例https://developer.mozilla.org/En/Using_audio_and_video_in_Firefox。
你可能会做这样的事情(未经测试):
var allMediaIds = ["audioLP", "audioATF", "vidScreen"];
var allMedia = [];
for (var i = 0, len = allMediaIds.length; i < len; i++) {
allMedia.push(document.getElementById(allMediaIds[i]));
}
function loopAllMedia(callback) {
for (var i = 0, len = allMedia .length; i < len; i++) {
callback(allMedia[i]);
}
}
loopAllMedia(function(element) {
element.addEventListener("play", function() {
loopAllMedia(function(otherElement) {
if (element != otherElement)
otherElement.pause();
});
});
});