1.检查元素是否在屏幕可见区域内
我们如何获得元素的点击率?
主要取决于用户点击元素的次数和元素在页面上显示的次数。
我们可以很容易地获取到用户的点击次数,但是如何获取一个元素的显示次数呢?
我们可以通过IntersectionObserver轻松实现,大家可以点击codepen体验一下实际效果。
<div class="tips">box is visible</div><div class="box">box</div><script>const $tips = document.querySelector('.tips')const callback = (entries) => {entries.forEach((entry) => {console.log(entry.intersectionRatio)if (entry.intersectionRatio > 0) {$tips.innerHTML = 'box is visible'} else if (entry.intersectionRatio <= 0) {$tips.innerHTML = 'box is hidden'}});}const options = {// A list of thresholds, sorted in increasing numeric order, where each threshold is a ratio of intersection area to bounding box area of an observed target. Notifications for a target are generated when any of the thresholds are crossed for that target. If no value was passed to the constructor, 0 is used.// threshold: 1,}const observer = new IntersectionObserver(callback, options)observer.observe(document.querySelector('.box'))</script>
2.深拷贝一个对象
我们经常使用 lodash 来深拷贝一个对象。
const obj = {a: {b: {name: 'fatfish'}}}const obj2 = lodash.cloneDeep(obj)obj2.a.b.name = 'medium'console.log(obj.a.b.name) // fatfishconsole.log(obj2.a.b.name) // medium
但这非常麻烦,因为我们必须下载整个库才能使用 cloneDeep。
幸运的是,在大多数情况下,我们可以使用这两种更简单的方式来深拷贝一个对象。
深度克隆1
const deepClone1 = (obj) => {return JSON.parse(JSON.stringify(obj))}const obj = {a: {b: {name: 'fatfish'}}}const obj2 = deepClone1(obj)obj2.a.b.name = 'medium'console.log(obj.a.b.name) // fatfishconsole.log(obj2.a.b.name) // medium
是的,我相信你已经看到了,deepClone1 有一些缺陷,它不能复制函数、正则表达式、未定义等值。
const deepClone1 = (obj) => {return JSON.parse(JSON.stringify(obj))}const obj = {a: {b: {name: 'fatfish'}},reg: /fatfish/gi,name: undefined,showName: (name) => console.log(name)}const obj2 = deepClone1(obj)console.log(obj2)/*{"a": {"b": {"name": "fatfish"}},"reg": {}}*/
深度克隆2
另一种方法是使用 structuredClone。
这非常方便,我们甚至可以不做任何处理就可以深拷贝一个对象。
它甚至可以复制正则表达式和未定义的。
const obj = {a: {b: {name: 'fatfish'}},reg: /fatfish/gi,name: undefined,}const obj2 = structuredClone(obj)obj2.a.b.name = 'medium'console.log(obj.a.b.name) // fatfishconsole.log(obj2.a.b.name) // mediumconsole.log(obj2)/*{"a": {"b": {"name": "medium"}},"reg": /fatfish/gi,"name": undefined}*/
但是真的没有缺点吗? 它在某些情况下也无法正常工作。
-
它不能复制功能
-
它不复制dom元素
-
ETC。
3.获取浏览器名称
在前端监控系统中,需要获取用户出错的浏览器。
这是获取主要浏览器名称的通用函数。
const getBrowserName = () => {const userAgent = window.navigator.userAgentconst browsers = {chrome: /chrome/i,safari: /safari/i,firefox: /firefox/i,ie: /internet explorer/i,edge: /edge/i,opera: /opera|opr/i,yandex: /yandex/i,uc: /ucbrowser/i,samsung: /samsungbrowser/i,maxthon: /maxthon/i,phantomjs: /phantomjs/i,crios: /crios/i,firefoxios: /fxios/i,edgios: /edgios/i,safariios: /safari/i,android: /android/i,ios: /(iphone|ipad|ipod)/i,unknown: /unknown/i}for (const key in browsers) {if (browsers[key].test(userAgent)) {return key}}return 'unknown'}// Execute the above code in chrome browserconsole.log(getBrowserName()) // chrome// Execute the above code in safari browserconsole.log(getBrowserName()) // safari
4.获取随机颜色
我怎样才能得到一个随机的有效颜色?
大家可以点击codepen链接体验实际效果。
const randomColor = () => {// Generate three random numbers as the three components of an RGB color valueconst r = Math.floor(Math.random() * 256);const g = Math.floor(Math.random() * 256);const b = Math.floor(Math.random() * 256);// Convert RGB color values to hexadecimal formatconst hexR = r.toString(16).padStart(2, '0');const hexG = g.toString(16).padStart(2, '0');const hexB = b.toString(16).padStart(2, '0');// Concatenated into a complete color value stringconst hexColor = `#${hexR}${hexG}${hexB}`;return hexColor;}
5.复制内容到剪贴板
为了给我们的网站用户提供更好的交互体验,我们经常需要提供将内容复制到剪贴板的功能。
难以置信的是,我们竟然只需要6行代码就可以实现这个功能。
const copyToClipboard = (content) => {const textarea = document.createElement("textarea")textarea.value = contentdocument.body.appendChild(textarea)textarea.select()document.execCommand("Copy")textarea.remove()}copyToClipboard('i love medium') // i love medium
6.从搜索中获取查询字符串
使用 URLSearchParams 解析搜索数据变得非常容易。
const getSearchParam = (name) => {const searchParams = new URLSearchParams(window.location.search)return searchParams.get(name)}// https://medium.com?name=fatfish&age=1000console.log(getSearchParam('name')) // fatfishconsole.log(getSearchParam('age')) // 1000
const getSearchParams = () => {const searchParams = new URLSearchParams(window.location.search)const params = {};for (const [ key, value ] of searchParams) {params[key] = value}return params}// https://medium.com?name=fatfish&age=1000getSearchParams() // { name: 'fatfish', age: 1000 }
7.将元素滚动到页面顶部
我们可以使用 scrollIntoView 方法将元素滚动到页面顶部。
甚至它可以提供非常流畅的用户体验。
const scrollToTop = (ele) => {ele.scrollIntoView({ behavior: "smooth", block: "start" })}document.querySelector('button').addEventListener('click', function () {scrollToTop(this)}, false)
8.将元素滚动到页面底部
将元素滚动到顶部是如此简单。
那我们要如何将元素滚动到页面底部?我想你已经猜到了,设置block结束即可。
const scrollToTop = (ele) => {ele.scrollIntoView({ behavior: "smooth", block: "end" })}document.querySelector('button').addEventListener('click', function () {scrollToTop(this)}, false)