点击海滩图标无法切换对应媒体资源的技术求助
问题:点击海滩图标无法切换对应音频与视频
我要实现点击beach图标时,播放对应的音频、视频,但点击后无法切换。已检查拼写、大小写、缩进,VS也无报错,怀疑问题在这段JS代码:
//pick different sound(S) sounds.forEach(sound =>{ sound.addEventListener('click', function(){ song.src = this.getAttribute('data-sound'); song.src = this.getAttribute('data-video'); checkPlaying(song); }); });
核心错误分析
- 元素赋值混淆:
song是获取到的<audio>元素,代码里把视频地址也赋值给它,直接覆盖了音频地址,导致音频无法加载;同时视频元素的src完全没被修改,自然不会切换视频。 - 播放状态未重置:切换资源时没有暂停当前播放、重置时间,会导致新资源加载后播放状态混乱。
- 音频src修改的潜在问题:原HTML中
<audio>使用了<source>标签,直接修改audio.src在部分浏览器可能不生效,需确保资源加载逻辑正确。
修正后的JavaScript代码
const app = () => { const song = document.querySelector('.song'); const play = document.querySelector('.play'); const outline = document.querySelector('.moving-outline circle'); const video = document.querySelector('.vid-container video'); const sounds = document.querySelectorAll('.sound-picker button'); const timeDisplay = document.querySelector('.time-display'); const timeselect = document.querySelectorAll('.time-select button'); const outlineLength = outline.getTotalLength(); let fakeDuration = 600; outline.style.strokeDasharray = outlineLength; outline.style.strokeDashoffset = outlineLength; // 切换音频/视频逻辑修正 sounds.forEach(sound =>{ sound.addEventListener('click', function(){ // 先暂停当前播放并重置进度 song.pause(); video.pause(); song.currentTime = 0; video.currentTime = 0; // 分别给音频、视频设置对应资源 song.src = this.getAttribute('data-sound'); video.src = this.getAttribute('data-video'); // 如果之前处于播放状态,切换后继续播放 const wasPlaying = !song.paused; if (wasPlaying) { song.play(); video.play(); } }); }); play.addEventListener("click", () => { checkPlaying(song); }); timeselect.forEach(option => { option.addEventListener('click', function() { fakeDuration = this.getAttribute("data-time"); timeDisplay.textContent = `${Math.floor(fakeDuration / 60)}:${Math.floor( fakeDuration % 60 )}`; }); }); const checkPlaying = song => { if(song.paused) { song.play(); video.play(); play.src= "./svg/pause.svg"; } else{ song.pause(); video.pause(); play.src = "./svg/play.svg"; } }; song.ontimeupdate = () => { let currentTime = song.currentTime; let elapsed = fakeDuration - currentTime; let seconds = Math.floor(elapsed % 60); let minutes = Math.floor(elapsed / 60); let progress = outlineLength - (currentTime / fakeDuration) * outlineLength; outline.style.strokeDashoffset = progress; timeDisplay.textContent = `${minutes}:${seconds}`; if (currentTime >= fakeDuration) { song.pause(); song.currentTime = 0; play.src = "./svg/play.svg"; video.pause(); } }; }; app();
补充说明
如果坚持使用<audio>内的<source>标签加载音频,可替换音频赋值逻辑为:
const audioSource = song.querySelector('source'); audioSource.src = this.getAttribute('data-sound'); song.load(); // 强制重新加载音频资源
内容的提问来源于stack exchange,提问作者NAVI
相关产品推荐
相关产品推荐

