前端js html css 基础巩固4

这是生成了不同的按钮 进行显示

每一个按钮对应一个音频

点击按钮 会播放对应的音频

直接上代码

复制代码
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        @import url('https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap');


        * {
            box-sizing: border-box;
        }

        body {
            background-color: rgb(161, 100, 223);
            font-family: 'Roboto', sans-serif;
            display: flex;
            flex-wrap: wrap;
            align-items: center;
            justify-content: center;
            text-align: center;
            height: 100vh;
            overflow: hidden;
            margin: 0;
        }

        .btn {
            background-color: rebeccapurple;
            border-radius: 3px;
            border: none;
            color: #fff;
            margin: 1rem;
            padding: 1.5rem 3rem;
            font-size: 1.2rem;
            font-family: inherit;
            cursor: pointer;
        }

        .btn:hover {
            opacity: .9;
        }

        .btn:focus {
            outline: none;
        }
    </style>
</head>

<body>
    <audio id="applause" src="./sounds/applause.mp3"></audio>
    <audio id="boo" src="./sounds/boo.mp3"></audio>
    <audio id="gasp" src="./sounds/gasp.mp3"></audio>
    <audio id="tada" src="./sounds/tada.mp3"></audio>
    <audio id="victory" src="./sounds/victory.mp3"></audio>
    <audio id="wrong" src="./sounds/wrong.mp3"></audio>
    <div id="buttons"></div>

    <script>
        const sounds = ['applause', 'boo', 'gasp', 'tada', 'victory', 'wrong'];
        sounds.forEach((sound) => {
            const btn = document.createElement('button')
            btn.classList.add('btn')
            btn.innerText = sound

            btn.addEventListener('click', () => {
                stopSongs()
                document.getElementById(sound).play()
            })
            document.getElementById("buttons").appendChild(btn)

        })

        function stopSongs() {
            sounds.forEach((sound) => {
                const song = document.getElementById(sound)
                song.pause()
                song.currrentTime = 0

            })
        }
    </script>







</body>

</html>

主要是考验的是 当前 生成 元素的语法 以及 audio 标签的使用 相关的播放 暂停的 方法

相关推荐
风铃喵游2 分钟前
构建引擎: 打造小程序编译器
前端·小程序·架构
_WndProc3 分钟前
【Python】Flask网页
开发语言·python·flask
sunbyte7 分钟前
50天50个小项目 (Vue3 + Tailwindcss V4) ✨ | ThemeClock(主题时钟)
前端·javascript·css·vue.js·前端框架·tailwindcss
小飞悟15 分钟前
🎯 什么是模块化?CommonJS 和 ES6 Modules 到底有什么区别?小白也能看懂
前端·javascript·设计
浏览器API调用工程师_Taylor16 分钟前
AOP魔法:一招实现登录弹窗的全局拦截与动态处理
前端·javascript·vue.js
FogLetter17 分钟前
初识图片懒加载:让网页像"懒人"一样聪明加载
前端·javascript
微客鸟窝18 分钟前
一文搞懂NVM管理Node.js:从安装到实战全攻略
前端
归于尽19 分钟前
Cookie、Session、JWT 的前世今生
前端
liujing1023292919 分钟前
Day04_刷题niuke20250703
java·开发语言·算法
程序员辉哥20 分钟前
学会在Cursor中使用Rules生成代码后可以躺平了吗?
前端·后端