自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

八種酷炫JavaScript 技巧

開發(fā) 前端
今天我們一起來了解一下八種酷炫JavaScript 技巧都有哪些吧。

1.檢查元素是否在屏幕可見區(qū)域內(nèi)

我們?nèi)绾潍@得元素的點擊率?

主要取決于用戶點擊元素的次數(shù)和元素在頁面上顯示的次數(shù)。

我們可以很容易地獲取到用戶的點擊次數(shù),但是如何獲取一個元素的顯示次數(shù)呢?

我們可以通過IntersectionObserver輕松實現(xiàn),大家可以點擊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.深拷貝一個對象

我們經(jīng)常使用 lodash 來深拷貝一個對象。

const obj = {
  a: {
    b: {
      name: 'fatfish'
    }
  }
}


const obj2 = lodash.cloneDeep(obj)


obj2.a.b.name = 'medium'
console.log(obj.a.b.name) // fatfish
console.log(obj2.a.b.name) // medium

但這非常麻煩,因為我們必須下載整個庫才能使用 cloneDeep。

幸運的是,在大多數(shù)情況下,我們可以使用這兩種更簡單的方式來深拷貝一個對象。

深度克隆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) // fatfish
console.log(obj2.a.b.name) // medium

是的,我相信你已經(jīng)看到了,deepClone1 有一些缺陷,它不能復(fù)制函數(shù)、正則表達式、未定義等值。

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。

這非常方便,我們甚至可以不做任何處理就可以深拷貝一個對象。

它甚至可以復(fù)制正則表達式和未定義的。

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) // fatfish
console.log(obj2.a.b.name) // medium
console.log(obj2)
/*
{
    "a": {
        "b": {
            "name": "medium"
        }
    },
    "reg": /fatfish/gi,
    "name": undefined
}
*/

但是真的沒有缺點嗎? 它在某些情況下也無法正常工作。

  • 它不能復(fù)制功能
  • 它不復(fù)制dom元素
  • ETC。

3.獲取瀏覽器名稱

在前端監(jiān)控系統(tǒng)中,需要獲取用戶出錯的瀏覽器。

這是獲取主要瀏覽器名稱的通用函數(shù)。

const getBrowserName = () => {
  const userAgent = window.navigator.userAgent
  const 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 browser
console.log(getBrowserName()) // chrome
// Execute the above code in safari browser
console.log(getBrowserName()) // safari

4.獲取隨機顏色

我怎樣才能得到一個隨機的有效顏色?

大家可以點擊codepen鏈接體驗實際效果。

const randomColor = () => {
  // Generate three random numbers as the three components of an RGB color value
  const 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 format
  const 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 string
  const hexColor = `#${hexR}${hexG}${hexB}`;
  return hexColor;
}

演示地址:https://codepen.io/qianlong/pen/qBJaOGO

5.復(fù)制內(nèi)容到剪貼板

為了給我們的網(wǎng)站用戶提供更好的交互體驗,我們經(jīng)常需要提供將內(nèi)容復(fù)制到剪貼板的功能。

難以置信的是,我們竟然只需要6行代碼就可以實現(xiàn)這個功能。

const copyToClipboard = (content) => {
  const textarea = document.createElement("textarea")
  textarea.value = content
  document.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 解析搜索數(shù)據(jù)變得非常容易。

const getSearchParam = (name) => {
  const searchParams = new URLSearchParams(window.location.search)
  return searchParams.get(name)
}


// https://medium.com?name=fatfish&age=1000
console.log(getSearchParam('name')) // fatfish
console.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=1000
getSearchParams() // { 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.將元素滾動到頁面底部

哇,太好了,將元素滾動到頂部是如此簡單。

朋友們,如何將元素滾動到頁面底部?我想你已經(jīng)猜到了,設(shè)置block結(jié)束即可。

const scrollToTop = (ele) => {
  ele.scrollIntoView({ behavior: "smooth", block: "end" })
}


document.querySelector('button').addEventListener('click', function () {
  scrollToTop(this)
}, false)

演示地址:https://codepen.io/qianlong/pen/mdzrVGK

總結(jié)

以上就是我這篇文章想與您分享的8個關(guān)于JavaScript的技巧,希望對您有用。

責(zé)任編輯:華軒 來源: web前端開發(fā)
相關(guān)推薦

2022-02-11 16:01:14

C語言技巧命令

2010-04-23 15:28:22

Windows組策略

2023-03-01 15:39:50

JavaScrip對象屬性ES6

2023-05-28 23:49:38

JavaScrip開發(fā)

2022-05-10 10:28:21

JavaScript代碼

2022-05-26 01:15:22

GitHub代碼快捷鍵

2022-09-21 13:32:39

Python裝飾器

2015-10-20 15:58:28

彈力菜單android源碼

2014-12-31 15:59:55

彈力菜單

2020-01-03 10:50:16

Python編程語言Mac電腦

2022-08-17 09:01:16

數(shù)據(jù)可視化大數(shù)據(jù)

2024-08-20 15:23:27

JavaScript開發(fā)

2024-05-30 08:01:52

2023-05-28 23:23:44

2014-09-01 15:49:18

智能穿戴智能設(shè)備可穿戴設(shè)備

2009-06-04 15:48:11

SUSE Linux解密

2017-05-02 09:55:02

2020-12-21 11:07:58

Python開發(fā)安裝

2020-05-14 10:36:34

Python數(shù)據(jù)開發(fā)

2024-05-29 05:00:00

點贊
收藏

51CTO技術(shù)棧公眾號