第212练的最终效果如下:
实现代码:
HTML:
<!DOCTYPE html><html lang=”en”><head><meta charset=”UTF-8″ /><meta http-equiv=”X-UA-Compatible” content=”IE=edge” /><meta name=”viewport” content=”width=device-width, initial-scale=1.0″ /><title>212练-掷骰子模拟器</title><link rel=”stylesheet” href=”index.css” /></head><body><h1>掷骰子模拟器</h1><div class=”dice” id=”dice”>⚄</div><button id=”roll-button”>掷骰子</button><ul id=”roll-history”></ul><script src=”index.js”></script></body></html>
CSS:
body {font-family: “Open Sans”, sans-serif;text-align: center;margin: 0;}h1 {font-size: 3rem;margin-top: 2rem;}.dice {font-size: 7rem;margin: 5px;animation-duration: 1s;animation-fill-mode: forwards;}.roll-animation {animation-name: roll;}@keyframes roll {0% {transform: rotateY(0deg) rotateX(0deg);}100% {transform: rotateY(720deg) rotateX(720deg);}}button {background-color: #47a5c4;color: white;font-size: 1.5rem;padding: 1rem 2rem;border: none;border-radius: 1rem;cursor: pointer;transition: background-color 0.3s ease;}button:hover {background-color: #2e8baf;}ul {list-style: none;padding: 0;max-width: 600px;margin: 2rem auto;}li {font-size: 1.5rem;padding: 0.5rem;margin: 0.5rem;background-color: #f2f2f2;border-radius: 0.5rem;box-shadow: 0 2px 2px rgba(0, 0, 0, 0.3);display: flex;justify-content: space-between;align-items: center;}li span {font-size: 3rem;margin-right: 1rem;}
JS:
const buttonEl = document.getElementById(“roll-button”);const diceEl = document.getElementById(“dice”);const rollHistoryEl = document.getElementById(“roll-history”);let historyList = [];function rollDice() {const rollResult = Math.floor(Math.random() * 6) + 1;const diceFace = getDiceFace(rollResult);diceEl.innerHTML = diceFace;historyList.push(rollResult);updateRollHistory();}function updateRollHistory() {rollHistoryEl.innerHTML = “”;for (let i = 0; i < historyList.length; i++) {const listItem = document.createElement(“li”);listItem.innerHTML = `掷 ${i + 1}: <span>${getDiceFace(historyList[i])}</span>`;rollHistoryEl.appendChild(listItem);}}function getDiceFace(rollResult) {switch (rollResult) {case 1:return “⚀”;case 2:return “⚁”;case 3:return “⚂”;case 4:return “⚃”;case 5:return “⚄”;case 6:return “⚅”;default:return “”;}}buttonEl.addEventListener(“click”, () => {diceEl.classList.add(“roll-animation”);setTimeout(() => {diceEl.classList.remove(“roll-animation”);rollDice();}, 1000);});
© 版权声明
文章版权归作者所有,未经允许请勿转载。
相关文章
暂无评论...