前端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 标签的使用 相关的播放 暂停的 方法

相关推荐
lsx20240616 小时前
HTML 音频(Audio)详解
开发语言
woshihonghonga16 小时前
【动手学深度学习】
开发语言·python
xuehuayu.cn16 小时前
js es6 class 类中的值是异步赋值, 子类中如何获取这个值?
javascript·es6
威风的虫16 小时前
ES6 数组方法:告别循环,拥抱函数式编程
开发语言·前端·javascript
小杨快跑~16 小时前
ES6 Promise:告别回调地狱的异步编程革命
前端·javascript·ecmascript·es6
码界筑梦坊16 小时前
240-基于Python的医疗疾病数据可视化分析系统
开发语言·python·信息可视化·数据分析·毕业设计·echarts
linweidong16 小时前
VIVO前端面试题及参考答案
前端·跨域·localstorage·重绘·浏览器兼容·git管理·前端重构
有意义16 小时前
从零搭建:json-server+Bootstrap+OpenAI 全栈 AI 小项目
前端·后端·llm
温宇飞16 小时前
CCState:为大型 Web 应用设计的状态管理库
前端
2301_8035545216 小时前
C++ 锁类型大全详解
开发语言·c++