const isBrowserTabInView = () => document.hidden;isBrowserTabInView();// Result: returns true or false depending on if tab is in view / focus
5. 检查数字是否为偶数
const timeFromDate = date => date.toTimeString().slice(0, 8);console.log(timeFromDate(new Date(2021, 0, 10, 17, 30, 0))); // Result: "17:30:00"console.log(timeFromDate(new Date()));// Result: will log the current time
7. 保留小数点(非四舍五入)
const elementIsInFocus = (el) => (el === document.activeElement);elementIsInFocus(anyElement)// Result: will return true if in focus, false if not in focus
9. 检查浏览器是否支持触摸事件
const touchSupported = () => { ('ontouchstart' in window || window.DocumentTouch && document instanceof window.DocumentTouch);}console.log(touchSupported());// Result: will return true if touch events are supported, false if not
10. 检查当前用户是否为苹果设备
我们可以使用 navigator.platform 来检查当前用户是否为苹果设备。
const isAppleDevice = /Mac|iPod|iPhone|iPad/.test(navigator.platform);console.log(isAppleDevice);// Result: will return true if user is on an Apple device
11. 滚动到页面顶部
window.scrollTo() 方法会取一个 x 和 y 坐标来进行滚动。如果我们将这些坐标设置为零,就可以滚动到页面的顶部。
注意:IE 不支持 scrollTo() 方法。
const goToTop = () => window.scrollTo(0, 0);goToTop();// Result: will scroll the browser to the top of the page
12. 获取所有参数平均值
我们可以使用 reduce 方法来获得函数参数的平均值。
const average = (...args) => args.reduce((a, b) => a + b) / args.length;average(1, 2, 3, 4);// Result: 2.5
13. 转换华氏度/摄氏度。(这个应该很少在国内用到吧)