gpt4 book ai didi

javascript - 通过按钮在歌曲之间切换

转载 作者:行者123 更新时间:2023-12-01 01:14:57 25 4
gpt4 key购买 nike

我正在尝试通过单击按钮在两首歌曲之间交换。我只需更改 src 就可以成功地交换歌曲一次,但是当我使用 if else 语句时,控件会“闪烁”,这意味着我的 if else 语句中一定有错误。

HTML

<div id = "audioplayer">
<p id="songname">Listen to Sisyphus by Have A Nice Life</p>
<audio id = "song"
controls
src="Untitled/10%20Sisyphus.mp3">
Your browser does not support the
<code>audio</code> element.
</audio>
</div>

<button onclick="myFunction()">Click to change songs</button>

JS:

function myFunction() {
if(document.getElementById("song").src === "Untitled/10%20Sisyphus.mp3") {

document.getElementById("songname").innerHTML = "listening to track03.mp3";
document.getElementById("song").src = "test.mp3";
}

else{

document.getElementById("songname").innerHTML = "Listen to Sisyphus by Have A Nice Life";
document.getElementById("song").src = "Untitled/10%20Sisyphus.mp3";



}
}

最佳答案

虽然您可以使用相对路径设置.src(例如“Untitled/10%20Sisyphus.mp”),但访问.src 属性将为您提供完整路径:

const song = document.getElementById("song");
song.src = "test.mp3";
console.log(song.src);
<audio id="song" controls src="Untitled/10%20Sisyphus.mp3"></audio>

因此,您只需将测试替换为完整路径即可,例如:

function myFunction() {
if (document.getElementById("song").src === "https://example.com/Untitled/10%20Sisyphus.mp3") {
// ...

实时片段(有效的 HTML,但没有实际的声音):

function myFunction() {
const song = document.getElementById("song");
const songname = document.getElementById("songname");
if (song.src === "https://stacksnippets.net/Untitled/10%20Sisyphus.mp3") {
songname.innerHTML = "listening to track03.mp3";
song.src = "test.mp3";
} else {
songname.innerHTML = "Listen to Sisyphus by Have A Nice Life";
song.src = "Untitled/10%20Sisyphus.mp3";
}
}
<div id="audioplayer">
<p id="songname">Listen to Sisyphus by Have A Nice Life</p>
<audio id="song" controls src="Untitled/10%20Sisyphus.mp3">
Your browser does not support the
<code>audio</code> element.
</audio>
</div>

<button onclick="myFunction()">Click to change songs</button>

关于javascript - 通过按钮在歌曲之间切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54848904/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com