我制作了一个有多个实例的快速音频播放器。单击播放时,播放 var将设置为true。如果有人点击 .playAudio 的其他实例,我正在尝试将 lastPlayed 实例设置为false。
我有一部分我评论了我无法弄清楚的部分。
JQUERY:
var lastPlay
var lastSelected
$('.playAudio').each(function(){
var audio = $(this).find('audio').get(0);
var playing = false
$(this).hover(function() {
if (playing) {
$(this).css({backgroundPosition: '-60px -60px'})
} else {
$(this).css({backgroundPosition: '0px -60px'})
}
},function() {
if (playing) {
$(this).css({backgroundPosition: '-60px 0'})
} else {
$(this).css({backgroundPosition: ''})
}
});
$(this).click(function(){
if (playing) {
playing = false
$(this).css({backgroundPosition: '0 60px'})
audio.currentTime = 0
audio.pause()
} else {
if (lastPlay) {
//** I'm trying to change the lastSelected's "playing" to false
lastPlay.pause()
}
playing = true
$(this).css({backgroundPosition: '-60px -60px'})
audio.play()
lastPlay = audio
lastSelected = $(this)
}
})
})
答案 0 :(得分:1)
这是一种方法:
var lastPlay,
lastSelected,
Audios = [];
$('.playAudio').each(function(i){
var Audio = {};
Audios[i] = Audio;
Audio.audio = $(this).find('audio').get(0);
Audio.playing = false;
$(this).hover(function() {
if (Audio.playing) {
$(this).css({backgroundPosition: '-60px -60px'});
} else {
$(this).css({backgroundPosition: '0px -60px'});
}
},function() {
if (Audio.playing) {
$(this).css({backgroundPosition: '-60px 0'});
} else {
$(this).css({backgroundPosition: ''});
}
});
$(this).click(function(){
if (Audio.playing) {
Audio.playing = false;
$(this).css({backgroundPosition: '0 60px'});
Audio.audio.currentTime = 0;
Audio.audio.pause();
} else {
if (lastPlay && Audios[lastPlay]) {
Audios[lastPlay].audio.pause();
Audios[lastPlay].playing = false;
}
Audio.playing = true;
$(this).css({backgroundPosition: '-60px -60px'});
Audio.audio.play();
lastPlay = i;
lastSelected = $(this);
}
});
});
我已经通过几种方式更改了您的脚本:
.each
的第一个参数,并将其用作音频播放器之间的唯一标识符<audio>
元素及其playing
状态保存在本地对象Audio
Audio
对象的引用存储为全局数组Audios
中的数组元素;使用唯一标识符作为索引lastPlay
现在只保存最后播放的音频元素的唯一标识符;我用它来访问Audios
数组中的相应对象,并在必要时设置相关性playing
。