2011-02-08 146 views
1

使用HTML5我在頁面上有2個音頻元素和1個視頻元素。 很簡單,我想添加JavaScript功能,防止它們同時播放。 我的主要問題是如何定位默認播放器的點擊事件。 HTML以下,謝謝;防止同時播放HTML5視頻和音頻元素

<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> 

回答

4

我怎麼會做這(使用jQuery爲簡單起見,雖然不是必需的):

$('audio,video').bind('play', function() { 
    activated = this; 
    $('audio,video').each(function() { 
    if(this != activated) this.pause(); 
    }); 
}); 
1

audiovideo元素有您可以捕捉的事件。例如參見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(); 
    }); 
    }); 
});