常用 Web API
setTimeout / setInterval
// setTimeout — 延遲執行一次
let timerId = setTimeout(() => {
console.log("3 秒後執行");
}, 3000); // ← 3000 毫秒 = 3 秒
clearTimeout(timerId); // ← 取消
// setInterval — 每隔 N 毫秒重複執行
let intervalId = setInterval(() => {
console.log("每 2 秒執行一次");
}, 2000);
clearInterval(intervalId); // ← 停止
URL 與 URLSearchParams
// 解析 URL
let url = new URL("https://example.com/path?name=小明&age=20#section");
console.log(url.hostname); // "example.com"
console.log(url.pathname); // "/path"
console.log(url.hash); // "#section"
console.log(url.searchParams.get("name")); // "小明"
// 建構查詢參數
let params = new URLSearchParams({ page: 1, limit: 10 });
params.append("sort", "name");
console.log(params.toString()); // "page=1&limit=10&sort=name"
History API
// 不重新載入頁面的情況下改變 URL
history.pushState({ page: 2 }, "", "/page/2"); // ← 新增歷史記錄
history.replaceState({ page: 3 }, "", "/page/3"); // ← 取代當前記錄
// 監聽上一頁/下一頁
window.addEventListener("popstate", (event) => {
console.log("導航到:", event.state);
});
Clipboard API
// 複製到剪貼簿
async function copyText(text) {
await navigator.clipboard.writeText(text);
console.log("已複製!");
}
// 讀取剪貼簿
async function pasteText() {
let text = await navigator.clipboard.readText();
console.log("剪貼簿內容:", text);
}
Intersection Observer
// 偵測元素是否進入畫面(懶載入、無限滾動)
let observer = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (entry.isIntersecting) { // ← 元素進入畫面
entry.target.classList.add("visible");
observer.unobserve(entry.target); // ← 觸發後停止觀察
}
});
}, {
threshold: 0.1 // ← 出現 10% 就觸發
});
// 觀察所有 .lazy 元素
document.querySelectorAll(".lazy").forEach(el => {
observer.observe(el);
});
Web Storage 事件
// 監聽其他分頁的 localStorage 變化
window.addEventListener("storage", (event) => {
console.log("Key:", event.key);
console.log("舊值:", event.oldValue);
console.log("新值:", event.newValue);
});
// 注意:只有「其他」分頁的變化會觸發,自己的不會
通知 API
// 請求通知權限
async function requestNotification() {
let permission = await Notification.requestPermission();
if (permission === "granted") {
new Notification("DevLearn", {
body: "你有新的學習任務!",
icon: "/images/logo.png"
});
}
}
地理定位
// 取得使用者位置
navigator.geolocation.getCurrentPosition(
(position) => {
console.log("緯度:", position.coords.latitude);
console.log("經度:", position.coords.longitude);
},
(error) => {
console.error("定位失敗:", error.message);
}
);