为所有音频元素添加一个.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();