青训营笔记 | 常见的 JavaScript 函数

79 阅读1分钟

生成随机颜色

const generateRandomHexColors = () =>${Math.floor(Math.random()  0xffffff).toString(16)};
console.log(generateRandomHexColors());

复制到剪贴板

const copyToClipboard = (text) => navigator.clipboard && avigator.clipboard.writeText && navigator.clipboard.writeText(text); 

copyToClipboard('Hello World!'); // JavaScript navigator 对象

检测深色主题

const isDarkMode = () => window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches; 

console.log(isDarkMode());

滚动到顶部、滚动到底部

// 滚动到顶部  
const scrollToTop = (element) => element.scrollIntoView({ behavior: 'smooth', block: 'start' });

// 滚动到底部  
const scrollToBottom = (element) => element.scrollIntoView({ behavior: 'smooth', block: 'end' });

检测元素是否在屏幕上

const callback = (entries) => {  
entries.forEach((entry) => {  
        if (entry.isIntersecting) {  
            console.log(`${entry.target.id} is visible`);  
        }  
   });  
};

const options = {  
    threshold: 1.0,  
};  

const observer = new IntersectionObserver(callback, options);  
const btn = document.getElementById('btn');  
const bottomBtn = document.getElementById('bottom-btn');  
observer.observe(btn);  
observer.observe(bottomBtn);

检测设备

const detectDeviceType = () => /AndroidlwebosliPhoneliPadliPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ? 'Mobile' : 'Desktop';

console.log(detectDeviceType());

从 URL 获取参数

const getParamByUrl = (key) => { 
    const url = new URL(location.href); 
   
    return url.searchParams.get(key); 
 };

深拷贝对象

const deepCopy = (obj) => JSONparse(JSON.stringify(obj));