原本我應該是接續DOM的基本練習,不過今天在youtube上看到一個超有意思的教學影片,一步步照著做之後挺有成就感的! 在此做個簡單的紀錄。
我先補上HTML、CSS 跟JS的結構
HTML結構
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<link
href="https://fonts.googleapis.com/css?family=Raleway"
rel="stylesheet"
/>
<link rel="stylesheet" href="./style.css" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Tap Music</title>
</head>
<body>
<section class="app">
<header>
<h1>Tap Music</h1>
<p>Create sounds with just one tap</p>
</header>
<div class="visual"></div>
<div class="pads">
<div class="pad1">
<audio src="./sounds/bubbles.mp3" class="sound"></audio>
</div>
<div class="pad2">
<audio class="sound">
<source src="./sounds/clay.mp3" />
</audio>
</div>
<div class="pad3">
<audio class="sound">
<source src="./sounds/confetti.mp3" />
</audio>
</div>
<div class="pad4">
<audio class="sound">
<source src="./sounds/glimmer.mp3" />
</audio>
</div>
<div class="pad5">
<audio class="sound">
<source src="./sounds/moon.mp3" />
</audio>
</div>
<div class="pad6">
<audio class="sound">
<source src="./sounds/ufo.mp3" />
</audio>
</div>
</div>
</section>
<script src="index.js"></script>
</body>
</html>
CSS樣式
//reset
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
font-family: "Raleway", sans-serif;
}
--------------------------------------------------------------
.app {
min-height: 100vh;
display: flex;
flex-direction: column;
justify-content: space-between;
align-items: center;
}
header h1 {
margin: 50px 0px 30px 0px;
text-align: center;
font-size: 40px;
}
header p {
font-size: 25px;
}
.pads {
background: lightblue;
width: 100%;
display: flex;
}
.pads > div {
height: 100px;
width: 100px;
flex: 1;
}
.pad1 {
background: #60d394;
}
.pad2 {
background: #d36060;
}
.pad3 {
background: #c060d3;
}
.pad4 {
background: #d3d160;
}
.pad5 {
background: #606bd3;
}
.pad6 {
background: #60c2d3;
}
.visual > div {
position: absolute;
bottom: 0%;
height: 50px;
width: 50px;
border-radius: 50%;
transform: scale(1);
z-index: -1;
}
@keyframes jump {
0% {
bottom: 0%;
left: 20%;
}
50% {
bottom: 50%;
left: 50%;
}
100% {
bottom: 00%;
left: 80%;
}
}
JS部分
window.addEventListener("load", () => {
const sounds = document.querySelectorAll(".sound");
const pads = document.querySelectorAll(".pads div");
const visual = document.querySelector(".visual");
const colors = [
"#60d394",
"#d36060",
"#c060d3",
"#d3d160",
"#606bd3",
"#60c2d3"
];
pads.forEach((pad, index) => {
pad.addEventListener("click", function() {
sounds[index].currentTime = 0;
sounds[index].play();
createBubble(index);
});
});
const createBubble = index => {
//Create bubbles
const bubble = document.createElement("div");
visual.appendChild(bubble);
bubble.style.backgroundColor = colors[index];
bubble.style.animation = `jump 1s ease`;
bubble.addEventListener("animationend", function() {
visual.removeChild(this);
});
};
});