js实现歌词自动轮转及播放时间跳转

需求

实现歌词滚动提示和歌词点击跳转功能

思路

歌词滚动:将歌词解析成两个数组,一个用于存放时间,一个用于存放歌词,下标一致对应,利用定时器对每毫秒轮询时间数组,若一致,显示歌词变红。
歌词点击播放:判断点击歌词在数组中的下标,读取时间数组中的时间,赋值播放时间

代码

歌词滚动.html

<html>
    <head>
        <title>歌词滚动</title>

        <script src="歌词滚动.js"></script>

    </head>
    <body>

        <div id="wordBox" style="width: 450px;height: 160px;background-color: aqua;overflow-y: scroll;display: flexl;flex-direction: column;justify-content: center;align-items: center;"></div>

    </body>
</html>

歌词滚动.json

window.onload = function () {


    var words = `[00:02.05]愿得一人心
[00:08.64]词:胡小健 曲:罗俊霖
[00:11.14]演唱: 李行亮,雨宗林
[00:24.93]
[00:27.48]曾在我背包小小夹层里的那个人
[00:32.31]陪伴我漂洋过海经过每一段旅程
[00:37.38]隐形的稻草人 守护我的天真
[00:42.43]曾以为爱情能让未来只为一个人
[00:47.50]关了灯依旧在书桌角落的那个人
[00:52.68]变成我许多年来纪念爱情的标本
[00:57.57]消失的那个人 回不去的青春
[01:02.69]忘不了爱过的人才会对过往认真
[01:09.71]只愿得一人心 白首不分离
[01:14.71]这简单的话语 需要巨大的勇气
[01:19.73]没想过失去你 却是在骗自己
[01:25.34]最后你深深藏在我的歌声里`

    // alert("hello")

    var wordArray = words.split("\n")

    var box = document.getElementById("wordBox")
    var time = []
    var wd = []
    for (let i = 0; i < wordArray.length; i++) {

        min = parseInt(wordArray[i].match(/\d{2}:\d{2}.\d{2}/)[0].split(":")[0])
        sin = parseInt(wordArray[i].match(/\d{2}:\d{2}.\d{2}/)[0].split(":")[1].split(".")[0])
        msin = parseInt(wordArray[i].match(/\d{2}:\d{2}.\d{2}/)[0].split(":")[1].split(".")[1])


        time.push(min * 60 * 1000 + sin * 1000 + msin)
    }

    var loadWords = function () {
        for (let j = 0; j < time.length; j++) {
            box.innerHTML = box.innerHTML + "<div style='width: 400px;height: 30px;margin-top: 10px;margin-bottom: 10px;' id=word" + j + "><span>" + wordArray[j] + "</span><button id=button" + j + ">点我</button></div>"
        }
    }

    loadWords()



    console.log(box.childNodes)

    console.log(time)
    var t1 = 0
    var interval = function () {
        setInterval(

            function () {



                for (let j = 0; j < time.length; j++) {

                    if (t1 == time[j]) {

                        for (let i = 0; i < box.childNodes.length; i++) {
                            box.childNodes[i].style.color = "black"
                        }
                        document.getElementById("word" + j).style.color = "red"

                        if (j > 1) {

                            box.scrollTo(0, parseInt(40 * (j - 1)))
                        }

                    }


                    if (t1 == time[time.length - 1]) {
                        window.clearInterval(interval)
                    }

                }
                t1 = t1 + 1

            },
            1
        )
    }
    interval()

    for (let i = 0; i < time.length; i++) {
        document.getElementById("button" + [i]).onclick = function () {
            t1 = time[i]
            interval()
        }
    }
}
posted @ 2024-05-25 17:21  酒暖=  阅读(30)  评论(0编辑  收藏  举报