jQuery播放音乐

严兴言
2023-12-01

通过jQuery播放mp3音乐

<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <script th:src="@{/static/js/jquery-3.6.0.js}"></script>
</head>
<body>
	<audio autoplay="autoplay" id="audio" loop="loop">
        <source th:src="@{/static/music/BGM.mp3}" type="audio/MP3">
    </audio>
    <img id="player" class="music_img" th:src="@{/static/music/music-note.png}" alt="">
</body>
<script>
    $(function () {
        let music = $("#audio")[0]; // jQuery对象转dom对象
        let musicImg = $("#player");
        // setTimeout(() => {music.play();}, 1000);  // 1s后自动播放
        musicImg.click(function () {  // 点击图标:播放 or 暂停
           if (music.paused) {
               music.play();
           } else
               music.pause();
        });
    })
</script>
</html>
 类似资料: