进阶技巧
Web APIs 精选
IntersectionObserver 可视监听、MutationObserver 变动、Clipboard API
Web APIs 精选
浏览器内置了大量好用 API——不依赖任何库,直接用。IntersectionObserver 比 scroll 事件高效百倍。
学完本章你将: 掌握 IntersectionObserver、MutationObserver、Clipboard API。
IntersectionObserver —— 元素可见性
javascript
// 懒加载图片
const observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
const img = entry.target;
img.src = img.dataset.src; // 加载真实图片
observer.unobserve(img); // 加载后停止观察
}
});
}, { threshold: 0.1 });
document.querySelectorAll("img[data-src]").forEach(img => {
observer.observe(img);
});
MutationObserver —— DOM 变动监听
javascript
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
mutation.addedNodes.forEach(node => {
console.log("新增节点:", node);
});
});
});
observer.observe(document.body, {
childList: true, // 子节点增删
attributes: true, // 属性变化
subtree: true, // 监听所有后代
});
Clipboard API
javascript
// 写入剪贴板
await navigator.clipboard.writeText("Hello, World!");
// 读取剪贴板(需要用户授权)
const text = await navigator.clipboard.readText();
console.log(text);
// 复制图片
const img = await fetch("image.png").then(r => r.blob());
await navigator.clipboard.write([
new ClipboardItem({ "image/png": img }),
]);