
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: /inte.NET 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;}
演示地址:https://codepen.io/qianlong/pen/qBJaOGO
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
演示地址:https://codepen.io/qianlong/pen/PoyGZYO
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 }
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)
演示地址:https://codepen.io/qianlong/pen/mdzrVGK
總結
以上就是我這篇文章想與您分享的8個關于JavaScript的技巧,希望對您有用,如果您覺得還不錯的話,請記得點贊我,關注我,并將它分享給您的開發者朋友,也許能夠幫助到他。
最后,感謝您的閱讀。






