【JavaScript】照片庫
阿新 • • 發佈:2020-07-16
以下內容為學習記錄,可以參考 MDN 原文。
環境
- vscode 1.46
- Microsoft Edge 83
html 模板
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>照片庫</title> <link rel="stylesheet" href="style.css"> </head> <body> <h1>照片庫示例</h1> <div class="full-img"> <img class="displayed-img" src="images/pic1.jpg"> <div class="overlay"></div> <button class="dark">變暗</button> </div> <div class="thumb-bar"> </div> <script src="main.js"></script> </body> </html>
樣式表
h1 { font-family: sans-serif; text-align: center; } body { width: 640px; margin: 0 auto; } .full-img { position: relative; display: block; width: 640px; height: 480px; } .overlay { position: absolute; top: 0; left: 0; width: 640px; height: 480px; background-color: rgba(0,0,0,0); } button { border: 0; background: rgba(150,150,150,0.6); text-shadow: 1px 1px 1px white; border: 1px solid #999; position: absolute; cursor: pointer; top: 2px; left: 2px; } .thumb-bar img { display: block; width: 20%; float: left; cursor: pointer; }
定義變數
const displayedImage = document.querySelector(".displayed-img");
const thumbBar = document.querySelector(".thumb-bar");
const btn = document.querySelector("button");
const overlay = document.querySelector(".overlay");
圖片列表
/* 新增圖片迴圈 */ for (let i = 1; i < 6; i++) { const newImage = document.createElement("img"); newImage.setAttribute("src", "images/pic" + i + ".jpg"); thumbBar.appendChild(newImage); }
切換圖片
/* 切換圖片 */
thumbBar.addEventListener("click", function(event) {
const src = event.target.getAttribute("src");
displayedImage.setAttribute("src", src);
});
變亮和變暗
addEventListener 和 removeEventListener 可以增加和刪除事件。
/* 編寫 變暗/變數 按鈕功能 */
btn.addEventListener("click", function(event) {
const color = event.target.getAttribute("class");
if (color === "dark") {
btn.setAttribute("class", "light");
btn.textContent = "變亮";
overlay.style.backgroundColor = "rgba(0, 0, 0, 0.5)";
} else {
btn.setAttribute("class", "dark");
btn.textContent = "變暗";
overlay.style.backgroundColor = "rgba(0, 0, 0, 0)";
}
});