Add a .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();
}
});
Update:
感谢您的及时回复! Grimbode,我已经尝试过你的方法
建议,这似乎有效。然而有能力阻止吗
并重置而不仅仅是暂停 - 所以如果他们点击1 https://stackoverflow.com/questions/17636310/play-audio-and-restart-it-onclick然后 [2]
前1 https://stackoverflow.com/questions/17636310/play-audio-and-restart-it-onclick完成,然后点击1 https://stackoverflow.com/questions/17636310/play-audio-and-restart-it-onclick再说一遍,那个1 https://stackoverflow.com/questions/17636310/play-audio-and-restart-it-onclick将从
重新开始而不是暂停的地方?和
有没有办法检查“全局”状态,然后添加代码
每个单独的音频文件 - 只是为了保留代码量和
重复减少?再次感谢!! –
Yes. 播放音频并单击重新启动 https://stackoverflow.com/questions/17636310/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();