js篇
千分位转换
new Intl.NumberFormat("zh-CN").format(1234567);
无依赖复制
try {
await navigator.clipboard.writeText("COUPON2123025");
} catch (err) {
alert("复制失败,请手动复制");
}
};
一键唤起系统分享
title: "我的新文章",
text: "快来看看",
url: location.href,
});
页面显示隐藏
document.visibilityState === "hidden"
? console.log("隐藏")
: console.log("显示");
});
DOM元素尺寸变化监听 ResizeObserver 时js原生Api 尺寸变化时执行回掉函数,检测width和height,不需要监听window.resize
window.addEventListener(
"resize",
debounce(() => {
const width = container.offsetWidth;
adjustElements(width);
}, 200),
);
const resizeObserver = new ResizeObserver(entries => {
for (let entry of entries) {
console.log('Element:', entry.target);
console.log('Content Rect:', entry.contentRect);
console.log('Width:', entry.contentRect.width);
console.log('Height:', entry.contentRect.height);
}
});
const element = document.querySelector('#myElement');
resizeObserver.observe(element);
URL.creactObjectURL 创建Blob或File对象的零食url(需要手动释放内存)
// 导出Blob数据为可下载链接
const blob = new Blob([JSON.stringify(data)], {type: 'application/json'})
const url = URL.createObjectURL(blob)
const a = document.createElement('a')
a.href = url
a.download = 'data.json'
a.click()
//释放内存
URL.revokeObjectURL(url)