为所有音频元素添加.audio
类,并在单击音频时循环播放所有音频元素。
$(".bridget-strevens").click(function() {
$('.audio').each(function (index, value) {
if (!value.paused) {
value.pause();
}
});
var audio = $('#bridget-strevens-intro')[0];
if (audio.paused) {
audio.play();
} else {
audio.pause();
}
});
如果这似乎太重了,你再简单地在一个全局变量添加音频元素如:
var currentAudio;
点击一个新的音频然后当,只是暂停的那一个,打新并使用当前正在播放的新元素更新currentAudio
变量。
var currentAudio = null;
$(".bridget-strevens").click(function() {
if(currentAudio != null && !currentAudio.paused){
currentAudio.pause();
}
var audio = $('#bridget-strevens-intro')[0];
if (audio.paused) {
audio.play();
currentAudio = audio;
} else {
audio.pause();
}
});
更新:
感谢您的迅速回应! Grimbode,我试过你的建议,这似乎是有效的。但是有没有停止 和重置,而不仅仅是暂停的能力 - 所以,如果他们点击1然后按[2] 1之前完成,然后再次单击1,即1将从 开始再次开始,而不是在该点它已暂停? 是否有任何方式检查'全局'状态,然后为每个单独的音频文件添加代码 - 只是为了保持代码量和 重复?再次感谢!! -
是的。 Play audio and restart it onclick详细解释了如何做到这一点。最终结果如下所示:
var currentAudio = null;
$(".bridget-strevens").click(function() {
if(currentAudio != null && !currentAudio.paused && currentAudio != this){
currentAudio.pause();
//Here we reset the audio and put it back to 0.
currentAudio.currentTime = 0;
}
var audio = $('#bridget-strevens-intro')[0];
if (audio.paused) {
audio.play();
currentAudio = audio;
} else {
audio.pause();
}
});
您无法真正优化代码。您将在每个音频元素上应用点击事件。您将不得不保留当前播放的音频元素,以便不必循环播放所有音频文件。
如果你真的想进一步,你可以创建一个库来处理所有事情。这里有一个例子:
(function(){
var _ = function(o){
if(!(this instanceof _)){
return new _(o);
}
if(typeof o === 'undefined'){
o = {};
}
//here you set attributes
this.targets = o.targets || {};
this.current = o.current || null;
};
//create fn shortcut
_.fn = _.prototype = {
init: function(){}
}
//Here you create your methods
_.fn.load = function(){
//here you load all the files in your this.targets.. meaning you load the source
//OR you add the click events on them.
//returning this for chainability
return this
};
//exporting
window._ = _;
})();
//here is how you use it
_({
targets: $('.audio')
}).load();
[?HTML5音频播放器 - jQuery的切换点击PLAY/PAUSE]的可能的复制(http://stackoverflow.com/questions/2988050/html5-audio-player-jquery-toggle-点击播放暂停) –
也许'audio.currentTime'对你很有趣?像'if(audio.currentTime> 0){/ *开始一个新的音频* /}' –