原生js音乐播放器搜索功能
时间: 2023-10-15 17:04:27 浏览: 140
带搜索功能的音乐播放器
实现一个原生JavaScript音乐播放器搜索功能可以按照以下步骤进行:
1. 定义一个搜索框,用于用户输入歌曲名称或歌手名称。
```html
<input type="text" id="searchInput" placeholder="Search...">
```
2. 获取搜索框中的输入内容。
```javascript
const searchInput = document.getElementById("searchInput");
const searchText = searchInput.value;
```
3. 遍历歌曲列表,查找包含搜索内容的歌曲,并将其显示在页面上。
```javascript
const songs = [
{
title: '歌曲1',
artist: '歌手1',
src: 'song1.mp3'
},
{
title: '歌曲2',
artist: '歌手2',
src: 'song2.mp3'
},
{
title: '歌曲3',
artist: '歌手3',
src: 'song3.mp3'
}
];
const searchSongs = (searchText) => {
// 遍历歌曲列表,查找包含搜索内容的歌曲
const filteredSongs = songs.filter((song) => {
return song.title.includes(searchText) || song.artist.includes(searchText);
});
// 清空原来的列表
const songList = document.getElementById("songList");
songList.innerHTML = '';
// 将搜索结果显示在页面上
filteredSongs.forEach((song) => {
const li = document.createElement("li");
li.innerHTML = `<span>${song.title}</span><span>${song.artist}</span>`;
li.addEventListener("click", () => {
playSong(song);
});
songList.appendChild(li);
});
};
searchInput.addEventListener("input", () => {
const searchText = searchInput.value;
searchSongs(searchText);
});
```
4. 在页面中显示歌曲列表。
```html
<ul id="songList">
<li><span>歌曲1</span><span>歌手1</span></li>
<li><span>歌曲2</span><span>歌手2</span></li>
<li><span>歌曲3</span><span>歌手3</span></li>
</ul>
```
完整的代码示例如下:
```html
<!DOCTYPE html>
<html>
<head>
<title>Music Player</title>
</head>
<body>
<h1>Music Player</h1>
<input type="text" id="searchInput" placeholder="Search...">
<ul id="songList">
<li><span>歌曲1</span><span>歌手1</span></li>
<li><span>歌曲2</span><span>歌手2</span></li>
<li><span>歌曲3</span><span>歌手3</span></li>
</ul>
<script>
const songs = [
{
title: '歌曲1',
artist: '歌手1',
src: 'song1.mp3'
},
{
title: '歌曲2',
artist: '歌手2',
src: 'song2.mp3'
},
{
title: '歌曲3',
artist: '歌手3',
src: 'song3.mp3'
}
];
const searchInput = document.getElementById("searchInput");
const songList = document.getElementById("songList");
const playSong = (song) => {
// 播放歌曲
};
const searchSongs = (searchText) => {
// 遍历歌曲列表,查找包含搜索内容的歌曲
const filteredSongs = songs.filter((song) => {
return song.title.includes(searchText) || song.artist.includes(searchText);
});
// 清空原来的列表
songList.innerHTML = '';
// 将搜索结果显示在页面上
filteredSongs.forEach((song) => {
const li = document.createElement("li");
li.innerHTML = `<span>${song.title}</span><span>${song.artist}</span>`;
li.addEventListener("click", () => {
playSong(song);
});
songList.appendChild(li);
});
};
searchInput.addEventListener("input", () => {
const searchText = searchInput.value;
searchSongs(searchText);
});
</script>
</body>
</html>
```
阅读全文