当按下播放时,再次单击时应该播放文件mp3,mp3应该暂停。目标是从'键'中获取文件名。然后在javascript / jquery中添加目录+ .mp3。
它的演奏但不是暂停。
<span class="play" key="cef83b993c716dd543b6fa4f053cc4a4">Play</span>
<script>
$(".play").click(function(){
var audio = new Audio("beats/" + $(this).attr('key') + ".mp3");
if (audio.paused) {
audio.play();
}
else {
audio.pause();
}
$( this ).toggleClass( "pause" ); // switch to some new css for a pause button
});
</script>
答案 0 :(得分:7)
原因是,每次点击它都会执行以下操作:
var audio = new Audio("beats/" + $(this).attr('key') + ".mp3");
所以你需要做的是,在前面添加一个条件:
var audio;
if (typeof audio == "undefined")
audio = new Audio("beats/" + $(this).attr('key') + ".mp3");
您的完整代码将是:
<span class="play" key="cef83b993c716dd543b6fa4f053cc4a4">Play</span>
<script>
var audio;
$(".play").click(function(){
if (typeof audio == "undefined")
audio = new Audio("beats/" + $(this).attr('key') + ".mp3");
if (audio.paused) {
audio.play();
}
else {
audio.pause();
}
$( this ).toggleClass( "pause" ); // switch to some new css for a pause button
});
</script>