网易云音乐歌曲功能(评论源代码分享)
页面效果:
页面一:
页面二:
页面三:
代码实现讲解:
// 定义路由表
const routers = [
{
name: "home",
//定义函数
component: homeComponent,
},
{
name: "about",
component: aboutComponent,
},
{
name: "recommend",
component: recommendComponent,
},
];
let hash;
function changeComponent() {
let options = getRouterOptions(hash);
// 查找对应的路由
const matchedRoute = routers.find((router) => router.name === options.name);
if (matchedRoute) {
// 执行对应的组件函数,传递解析的路由参数
matchedRoute.component(options);
} else {
// 如果找不到对应的路由,执行404组件
homeComponent()
}
}
window.addEventListener("hashchange", () => {
hash = window.location.hash;
changeComponent();
});
关于音乐播放的实现大家可以通过下面这个链接学习进行实现,功能是一样的【前端】-音乐播放器(源代码和结构讲解,大家可以将自己喜欢的歌曲添加到数据当中,js实现页面动态显示音乐)-CSDN博客
歌词实现动态效果思想:
1.获得播放歌词内容
2.通过歌词数据初始化当前歌词列表
3.通过获取audio对象,获取播放时间,然后通过将json中的对象中的时间进行解析成秒数,通过当前音乐时间找出应该播放哪句歌词,然后给当前歌词进行高光设置,并且将歌词进行改变(这些都通过audio时间变化进行监听调用,并且只有再歌词index改变时才有效果)
点击进度条进行音乐进度改变:
// 获取 DOM 元素
const progressBar = document.querySelector(".music-progress-bar");
const progressLine = document.querySelector(".music-progress-line");
const audio = document.querySelector("audio");
// 监听点击进度条事件
progressBar.addEventListener("click", function (e) {
// 获取进度条宽度
const progressBarWidth = progressBar.offsetWidth;
// 获取点击位置相对于进度条的距离
const clickX = e.offsetX;
// 计算点击位置的百分比
const percentage = clickX / progressBarWidth;
// 计算音乐要跳转到的时间
const newTime = percentage * audio.duration;
// 设置音乐播放时间
audio.currentTime = newTime;
// 更新进度条显示
updateProgressBar();
});
// 更新进度条显示函数
function updateProgressBar() {
const currentTime = audio.currentTime;
const duration = audio.duration;
// 计算播放进度百分比
const percentage = (currentTime / duration) * 100;
// 设置进度条宽度
progressLine.style.width = percentage + "%";
}
到这里大致思路讲解完了,大家如果有什么疑问可以私我!!!