1. 一键复制文本
function copyText(text) {
const input = document.createElement('input');
input.value = text;
document.body.appendChild(input);
input.select();
document.execCommand('copy');
document.body.removeChild(input);
}
2. 防抖 (Debounce)
const debounce = (fn, delay = 300) => {
let timer = null;
return (...args) => {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, args), delay);
};
};
3. 暗黑模式检测 & 切换
const darkMode = window.matchMedia('(prefers-color-scheme: dark)');
function toggleDark(isDark) {
document.documentElement.classList.toggle('dark', isDark);
}
toggleDark(darkMode.matches);
darkMode.addEventListener('change', e => toggleDark(e.matches));
4. 生成随机渐变背景
function randomGradient() {
const hue = ~~(Math.random() * 360);
return `linear-gradient(135deg, hsl(${hue}, 70%, 60%), hsl(${(hue + 40) % 360}, 70%, 60%))`;
}
document.body.style.background = randomGradient();
5. 本地 JSON 导出下载
function downloadJSON(data, filename = 'data.json') {
const blob = new Blob([JSON.stringify(data, null, 2)], {type: 'application/json'});
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url; a.download = filename;
a.click();
URL.revokeObjectURL(url);
}