每 3 秒自動切換背景圖片 (images/01.jpg ~ 06.jpg),循環播放。原代碼邏輯正確但冗餘,老板要求「更簡潔」。
原代碼可能使用了多個變量、冗長的 if-else 或 switch 判斷圖片索引,甚至手動拼接字符串。核心邏輯其實只有三步:計算索引 → 拼接路徑 → 設置樣式。
let pos = 0;
const imgs = 6; // 圖片總數
const baseUrl = 'images/0'; // 公共前綴
setInterval(() => {
pos = (pos % imgs) + 1; // 1→2→...→6→1 循環
document.body.style.background = `url(${baseUrl}${pos}.jpg) center/cover no-repeat`;
}, 3000);
| 原寫法痛點 | 優化方案 | 收益 |
|---|---|---|
手動 if(pos>5) pos=1 | 取模運算 (pos % 6) + 1 | 無邊界判斷,自動循環 |
字符串拼接 "url(images/0"+pos+".jpg)" | 模板字面量 `url(${baseUrl}${pos}.jpg)` | 可讀性強,易維護路徑 |
重複獲取 document.getElementsByTagName("body")[0] | 直接用 document.body | 簡潔、性能略優 |
使用 round 關鍵字 (非標準) | 標準 CSS center/cover no-repeat | 兼容性好,效果更可控 |
class BgCarousel {
constructor({ container = document.body, prefix = 'images/0', count = 6, interval = 3000 } = {}) {
this.container = container;
this.prefix = prefix;
this.count = count;
this.interval = interval;
this.pos = 0;
this.timer = null;
}
start() {
this.timer = setInterval(() => this.next(), this.interval);
}
next() {
this.pos = (this.pos % this.count) + 1;
this.container.style.background = `url(${this.prefix}${this.pos}.jpg) center/cover no-repeat`;
}
stop() { clearInterval(this.timer); }
}
// 使用
const carousel = new BgCarousel({ count: 6 });
carousel.start();
// 需要停止時:carousel.stop();
利用 取模運算實現循環索引、模板字面量拼接字符串、封裝為可復用類,即可將幾十行代碼壓縮為 10 行核心邏輯,同時提升可維護性與擴展性。這就是「簡單」的工程化含義。