我有一个与onClick事件绑定的函数.它应该播放一首歌.如果有一首歌已经播放,它应该停止当前的歌曲并开始播放新的歌曲.唯一的问题是,据我所知,只有一种暂停方法,这意味着前一首歌将从暂停位置而不是从头开始.有没有办法解决这个问题(比如.stop()方法)?
这是我的代码:
var currSong="";
function playSong(newSong){
alert(newSong);
if (newSong != ""){
if(currSong != "" ) {
document.getElementById(currSong).pause();
}
document.getElementById(newSong).play();
currSong = newSong;
}
}
Run Code Online (Sandbox Code Playgroud)
通过查看元素的MDC文档audio,看来正确的方法是设置currentTime属性:
function playSong(newSong){
alert(newSong);
if (newSong != ""){
if(currSong != "" ) {
document.getElementById(currSong).pause();
}
var newSongEl = document.getElementById(newSong);
newSongEl.currentTime = 0;
newSongEl.play();
currSong = newSong;
}
}
Run Code Online (Sandbox Code Playgroud)
此外,最好将相关元素存储在其中currSong,而不是存储在ID中,除非您将ID用于其他内容.