返回
24 个巧妙的 ES6 代码片段,轻松解决前端工作难题
前端
2023-09-17 04:19:42
随着 ES6 的普及,前端开发者掌握了一系列强大的工具,可以显著提升工作效率并解决棘手的难题。本文精挑细选了 24 个实用且创新的 ES6 代码片段,它们涵盖了从元素操作到事件处理等方方面面,旨在帮助您轻松应对前端开发中的各种挑战。
1. 隐藏指定元素
document.querySelectorAll('.hidden').forEach((el) => el.style.display = 'none');
2. 确认元素是否具有指定类
element.classList.contains('active');
3. 切换元素的类
element.classList.toggle('visible');
4. 获取当前页面的滚动位置
window.pageYOffset;
5. 滚动到页面顶部
window.scrollTo({
top: 0,
behavior: 'smooth'
});
6. 确认父元素是否包含子元素
parent.contains(child);
7. 确认指定元素是否可见
element.offsetParent !== null;
8. 获取元素的计算样式
getComputedStyle(element).getPropertyValue('width');
9. 监听元素的 hover 事件
element.addEventListener('mouseenter', () => {
// 执行 hover 操作
});
10. 创建可重复的函数
const repeat = (func, times) => {
for (let i = 0; i < times; i++) {
func();
}
};
11. 延迟执行函数
setTimeout(() => {
// 执行函数
}, 1000); // 延迟 1 秒
12. 创建一个函数队列
const queue = [];
const executeQueue = () => {
if (queue.length > 0) {
const next = queue.shift();
next();
setTimeout(executeQueue, 10);
}
};
13. 防抖函数
const debounce = (func, wait) => {
let timeout;
return (...args) => {
clearTimeout(timeout);
timeout = setTimeout(() => {
func.apply(this, args);
}, wait);
};
};
14. 节流函数
const throttle = (func, wait) => {
let inThrottle = false;
return (...args) => {
if (!inThrottle) {
func.apply(this, args);
inThrottle = true;
setTimeout(() => inThrottle = false, wait);
}
};
};
15. 创建一个深度克隆对象
const deepClone = (obj) => JSON.parse(JSON.stringify(obj));
16. 随机排列数组
const shuffleArray = (array) => array.sort(() => Math.random() - 0.5);
17. 获取 URL 参数
const urlParams = new URLSearchParams(window.location.search);
urlParams.get('param_name');
18. 设置 cookie
document.cookie = 'name=value; expires=date; path=/';
19. 获取 cookie
document.cookie.split(';').find((cookie) => cookie.startsWith('name=')).split('=')[1];
20. 检测移动设备
const isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
21. 获取浏览器语言
navigator.language;
22. 检测用户在线状态
navigator.onLine;
23. 获取系统主题
window.matchMedia('(prefers-color-scheme: dark)').matches;
24. 创建一个自定义事件
const customEvent = new CustomEvent('my-custom-event', {
detail: {
data: 'custom data'
}
});
document.dispatchEvent(customEvent);
掌握这些 ES6 代码片段,您将大幅提升前端开发效率,并轻松解决工作中遇到的各种难题。无论是操作元素、处理事件还是创建复杂的交互,这些片段都能为您提供强大的支持。