如何使用JavaScript为音板按钮添加过滤搜索栏
音效板搜索过滤功能实现
直接按下面两步修改代码即可:
1. 补全HTML结构
把原来的<!--Filter-->注释替换成搜索输入框,同时补上按钮容器(原JS逻辑里依赖id为buttons的容器,之前HTML未定义):
<h1>Dr s</h1> <h2>Sound board</h2> <!-- 搜索过滤栏 --> <input type="text" id="soundSearch" placeholder="搜索音效..."> <div id="buttons"></div>
记得提前把所有音效对应的<audio>标签加到页面里,id要和sounds数组里的音效名完全一致,否则点击按钮播放会报错。
2. 替换JS逻辑
直接用下面的代码替换原有JS,已经包含按钮渲染、实时搜索过滤、切歌自动停上一段音效的功能:
const sounds = [ 'Jason', 'lil Jon', 'mario', 'TwoClock', 'beep boppy', 'Dixon Cider', 'Baldy', 'PK Fire', 'look Eye', 'Show up' ]; const buttonsContainer = document.getElementById('buttons'); const searchInput = document.getElementById('soundSearch'); // 渲染全部音效按钮 sounds.forEach((sound) => { const btn = document.createElement('button'); btn.classList.add('btn'); btn.innerText = sound; // 预存小写格式的音效名,避免每次搜索重复转写 btn.dataset.soundName = sound.toLowerCase(); btn.addEventListener('click', () => { stopSongs(); document.getElementById(sound).play(); }); buttonsContainer.appendChild(btn); }); // 实时搜索过滤逻辑 searchInput.addEventListener('input', (e) => { const keyword = e.target.value.trim().toLowerCase(); document.querySelectorAll('.btn').forEach(btn => { btn.style.display = btn.dataset.soundName.includes(keyword) ? 'inline-block' : 'none'; }); }); // 停止所有正在播放的音效 function stopSongs() { sounds.forEach(sound => { const audio = document.getElementById(sound); audio.pause(); audio.currentTime = 0; }) }
实现说明
- 搜索采用大小写不敏感的模糊匹配规则,输入关键词只要是音效名的子串就能匹配到对应按钮,比如输入
fire会匹配到PK Fire,输入a会匹配所有名字带a的音效 - 输入时实时触发过滤,不需要额外点击搜索按钮
- 已经补全你之前预留的切歌停止功能:点击新音效时会自动暂停正在播放的其他音效,从头开始播放当前选中的音效
- 如果需要调整按钮显示/隐藏的样式,直接修改对应display属性值即可,比如改成块级元素就把
inline-block换成block
内容的提问来源于stack exchange,提问作者andre wellington
相关产品推荐
相关产品推荐

