我正在模板一個帶有卡片串列頁面的 HUGO 網站。我有來自每張卡內容的音頻檔案。這是html元素:
<audio class="podcast__audio" src="{{ $podcast.RelPermalink }}"></audio>
每張卡都有一個按鈕來播放音頻:
<button class="podcast__player_button">
<img class="podcast__player_play" src="/images/podcast/play.png">
</button>
在 Javascript 中,我使用此功能播放音頻:
const podcastAudio = document.querySelector('.podcast__audio');
function toggleAudio () {
if (podcastAudio.paused) {
podcastAudio.play();
} else {
podcastAudio.pause();
}
}
我在串列頁面上顯示了 4 張卡片,每張卡片都有一個不同的音頻檔案可以播放。
我在按鈕上有一個用于事件偵聽器的 for 回圈:
const podcastPlayerButton = document.querySelectorAll('.podcast__player_button');
for (let i = 0; i < podcastPlayerButton.length; i ) {
podcastPlayerButton[i].addEventListener('click', toggleAudio);
}
它作業正常,但它只切換頁面的第一個音頻檔案(這是有道理的),但我希望它播放鏈接到每張卡的音頻檔案。第一個podcast__player_button按鈕應該播放第一個podcast__audio檔案,第二個按鈕應該播放第二個音頻檔案,依此類推。
我想我需要querySelectorAll音頻檔案并對其進行迭代?如何對toggleAudio()正確的音頻檔案執行該功能?
uj5u.com熱心網友回復:
好的,因為按鈕和音頻檔案具有相同的索引,此代碼有效:
for (let i = 0; i < podcastPlayerButton.length; i ) {
podcastPlayerButton[i].addEventListener('click', function () {
if (podcastAudio[i].paused) {
podcastAudio[i].play();
} else {
podcastAudio[i].pause();
}
})
};
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/487855.html
標籤:javascript dom
