首页 文章 精选 留言 我的

精选列表

搜索[智能扫码],共10000篇文章
优秀的个人博客,低调大师

分享18个常用的ECMAScript 6代码片段

最近在整理电脑的项目,总结了一些常见的小功能(获取URL、URL参数解析、Form表单数据解析等),特别的reduce方法的妙用。 1.如何批量隐藏指定的元素? const hide = (...el) => [...el].forEach((e) => (e.style.display = "none")); // 调用示例 hide(document.querySelectorAll("img")); 2.如何检查元素是否具有指定的类? const hasClass = (el, className) => el.classList.contains(className); // 调用示例 hasClass(document.querySelector("p.special"), "special"); // true 3.如何切换元素的样式类? const toggleClass = (el, className) => el.classList.toggle(className); // 调用示例 toggleClass(document.querySelector("p.special"), "special"); 4.如何获取当前页面的滚动位置? const getScrollPosition = (el = window) => ({ x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft, y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop, }); // 调用示例 getScrollPosition(); // {x: 0, y: 100} 5.如何平滑滚动到页面顶部? const scrollToTop = () => { const scrollTop = document.documentElement.scrollTop || document.body.scrollTop; if (scrollTop > 0) { window.requestAnimationFrame(scrollToTop); window.scrollTo(0, scrollTop - scrollTop / 8); } }; // 调用示例 scrollToTop(); 6.如何检查父元素是否包含子元素? const elementContains = (parent, child) => parent !== child && parent.contains(child); // 调用示例 elementContains( document.querySelector("head"), document.querySelector("title") ); // true elementContains(document.querySelector("body"), document.querySelector("body")); // false 7.如何检查指定的元素在视窗中是否可见? const elementIsVisibleInViewport = (el, partiallyVisible = false) => { const { top, left, bottom, right } = el.getBoundingClientRect(); const { innerHeight, innerWidth } = window; return partiallyVisible ? ((top > 0 && top < innerHeight) || (bottom > 0 && bottom < innerHeight)) && ((left > 0 && left < innerWidth) || (right > 0 && right < innerWidth)) : top >= 0 && left >= 0 && bottom <= innerHeight && right <= innerWidth; }; // 调用示例 elementIsVisibleInViewport(el); // 不完全可见 elementIsVisibleInViewport(el, true); // 部分可见 8.如何获取元素中的所有图像? const getImages = (el, includeDuplicates = false) => { const images = [...el.getElementsByTagName("img")].map((img) => img.getAttribute("src") ); return includeDuplicates ? images : [...new Set(images)]; }; // 调用示例 getImages(document, true); // ['image1.jpg', 'image2.png', 'image1.png', '...'] getImages(document, false); // ['image1.jpg', 'image2.png', '...'] 9.如何确定该设备是移动设备还是桌面端? const detectDeviceType = () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test( navigator.userAgent ) ? "Mobile" : "Desktop"; // 调用示例 detectDeviceType(); // "移动端" or "桌面" 10.如何获取当前URL? const currentURL = () => window.location.href; // 调用示例 currentURL(); 11.将URL参数解析为对象? const getURLParameters = (url) => (url.match(/([^?=&]+)(=([^&]*))/g) || []).reduce( (a, v) => ( (a[v.slice(0, v.indexOf("="))] = v.slice(v.indexOf("=") + 1)), a ), {} ); // 调用示例 getURLParameters("http://url.com/page?n=DevPoint&s=Shenzhen"); // {n: 'DevPoint', s: 'Shenzhen'} getURLParameters("baidu.com"); // {} 12.如何将Form表单数据转为对象? const formToObject = (form) => Array.from(new FormData(form)).reduce( (account, [key, value]) => ({ ...account, [key]: value, }), {} ); // 调用示例 formToObject(document.querySelector("#form")); // { city: 'Shenzhen', name: 'DevPoint' } 13.延迟执行函数(毫秒)? const delay = (fn, wait, ...args) => setTimeout(fn, wait, ...args); delay( (text) => { console.log(text); }, 1000, "later" ); 14.如何删除DOM事件? const off = (el, evt, fn, opts = false) => el.removeEventListener(evt, fn, opts); const fn = () => console.log("!"); document.body.addEventListener("click", fn); off(document.body, "click", fn); 15.如何将时间戳转为直观的时间格式? const formatDuration = (ms) => { if (ms < 0) ms = -ms; const time = { day: Math.floor(ms / 86400000), hour: Math.floor(ms / 3600000) % 24, minute: Math.floor(ms / 60000) % 60, second: Math.floor(ms / 1000) % 60, millisecond: Math.floor(ms) % 1000, }; const timeZh = { day: "天", hour: "小时", minute: "分钟", second: "秒", millisecond: "毫秒", }; return Object.entries(time) .filter((val) => val[1] !== 0) .map(([key, val]) => `${val} ${timeZh[key]}`) .join(","); }; // 调用示例 formatDuration(1001); // 1 秒,1 毫秒 formatDuration(34325055574); // 397 天,6 小时,44 分钟,15 秒,574 毫秒 16.如何获得两个日期的时间差? const getDaysDiffBetweenDates = (dateInitial, dateFinal) => (dateFinal - dateInitial) / (1000 * 3600 * 24); // 调用示例,以天计算 getDaysDiffBetweenDates(new Date("2021-03-20"), new Date("2021-04-03")); // 14 17.如何将字符串复制到剪贴板? const copyToClipboard = (str) => { const el = document.createElement("textarea"); el.value = str; el.setAttribute("readonly", ""); el.style.position = "absolute"; el.style.left = "-9999px"; document.body.appendChild(el); const selected = document.getSelection().rangeCount > 0 ? document.getSelection().getRangeAt(0) : false; el.select(); document.execCommand("copy"); document.body.removeChild(el); if (selected) { document.getSelection().removeAllRanges(); document.getSelection().addRange(selected); } }; // 调用示例 copyToClipboard("DevPoint"); // 'DevPoint' copied to clipboard. 18.如何创建一个计数器? 指定一个DOM id,创建一个计数器,指定步长,结束数值,按照同样的频率计数。 const counter = (selector, start, end, step = 1, duration = 2000) => { let current = start; const _step = (end - start) * step < 0 ? -step : step; const timer = setInterval(() => { current += _step; document.querySelector(selector).innerHTML = current; if (current >= end) document.querySelector(selector).innerHTML = end; if (current >= end) clearInterval(timer); }, Math.abs(Math.floor(duration / (end - start)))); return timer; }; // 调用示例 counter("#counter", 1, 1000, 5, 2000); // 创建一个计数器,从1开始,步长为5,计数到1000结束 完

优秀的个人博客,低调大师

iOS 13.5.5代码暗示苹果正在开发服务套餐

据外媒报道,有传言称苹果正在开发一个服务套餐,它将提供多种苹果服务诸如Apple TV+、Apple Music,月费固定。据9to5Mac报道,iOS 13.5.5中的代码似乎证实了这一计划。在iOS 13.5.5的文件中发现了“bundle offer”和“bundle subscription”,而这些文件不在iOS的早期版本中。 这些文件据称跟“苹果自己的服务订阅管理系统如Apple News+有关”。 自2018年以来,苹果就一直被传正在准备某种服务套餐,并且大部分传闻都暗示这家公司考虑将Apple Music、Apple TV+和Apple News+整合到这个套餐中。 现在,Apple Music月费9.99美元,Apple TV+月费4.99美元、Apple News+月费9.99美元,所以套餐可能会将它们整合到一起之后带来一定的折扣价格。 自2019年底以来,苹果一直在跟唱片公司讨论创建一个媒体内容套餐的计划。然而至少有一家唱片公司对此表达了担忧,因此目前还不清楚苹果何时能就此事达成协议。按照彭博社去年11月份的一篇报道暗示,这一服务最快可能会在2020年推出。 实际上在去年年底的时候,这家公司曾尝试过推出服务套餐,其为订阅了Apple Music的学生免费提供了Apple TV+服务。

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Rocky Linux

Rocky Linux

Rocky Linux(中文名:洛基)是由Gregory Kurtzer于2020年12月发起的企业级Linux发行版,作为CentOS稳定版停止维护后与RHEL(Red Hat Enterprise Linux)完全兼容的开源替代方案,由社区拥有并管理,支持x86_64、aarch64等架构。其通过重新编译RHEL源代码提供长期稳定性,采用模块化包装和SELinux安全架构,默认包含GNOME桌面环境及XFS文件系统,支持十年生命周期更新。

WebStorm

WebStorm

WebStorm 是jetbrains公司旗下一款JavaScript 开发工具。目前已经被广大中国JS开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。与IntelliJ IDEA同源,继承了IntelliJ IDEA强大的JS部分的功能。

用户登录
用户注册