以下內容為學習記錄,可以參考 MDN 原文。
環境
- vscode 1.46
- Microsoft Edge 83
新建 html 文檔
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width">
<title>笑話機</title>
<link href="style.css" rel="stylesheet">
</head>
<body>
<div>
<label for="customname">輸入自定義名字:</label>
<input id="customname" type="text" placeholder="李雷">
</div>
<div>
<button class="randomize">生成隨機笑話</button>
</div>
<!-- 鳴謝:Willy Aguirre 提供的測試代碼 -->
<p class="story"></p>
<script src="main.js"></script>
</body>
</html>
定義樣式表
body {
font-family: sans-serif;
width: 350px;
}
label {
font-weight: bold;
}
div {
padding-bottom: 20px;
}
input[type="text"] {
padding: 5px;
width: 150px;
}
p {
background: #FFC125;
color: #5E2612;
padding: 10px;
visibility: hidden;
}
生成笑話
新建一個 main.js 文件,需要在 html 文檔中引入。
選擇頁面元素
const customName = document.getElementById("customname");
const randomize = document.querySelector(".randomize");
const story = document.querySelector(".story");
獲取數組隨機元素
function randomValueFromArray(array) {
return array[Math.floor(Math.random() * array.length)];
}
定義基礎變量
const storyText = "今天氣溫 34 攝氏度,:inserta:出去遛彎。當走到:insertb:門前時,突然就:insertc:。" +
"人們都驚呆了,李雷全程目睹但並沒有慌,因為:inserta:是一個 130 公斤的胖子,天氣又辣么熱。";
const insertX = ["怪獸威利", "大老爹", "聖誕老人"];
const insertY = ["肯德基", "迪士尼樂園", "白宮"];
const insertZ = ["自燃了", "在人行道化成了一坨泥", "變成一條鼻涕蟲爬走了"];
綁定點擊事件
randomize.addEventListener("click", result);
實現笑話生成
function result() {
const xItem = randomValueFromArray(insertX);
const yItem = randomValueFromArray(insertY);
const zItem = randomValueFromArray(insertZ);
let newStory = storyText.replace(":inserta:", xItem).replace(":inserta:", xItem)
.replace(":insertb:", yItem).replace(":insertc:", zItem);
if (customName.value !== "") {
const name = customName.value;
newStory = newStory.replace("李雷", name);
}
story.textContent = newStory;
story.style.visibility = "visible";
}