成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

JS小知識,分享工作中常用的八個封裝函數,讓你事半功倍

開發 后端
工作中經常用到的 8 個Javascript方法,記住并收藏這些方法,避免重新發明輪子。

一、回到頂部

當頁面很長時,如果用戶想回到頁面頂部,必須滾動滾動鍵幾次才能回到頂部。如果頁面右下角有“返回頂部”按鈕,用戶可以點擊返回頂部。對于用戶來說,這是一個很好的用戶體驗。

// Method 1
  constbindTop1 = () => {
      window.scrollTo(0, 0)
      document.documentElement.scrollTop = 0;
  }
  
  
    // Method 2: Scrolling through the timer will be visually smoother, without much lag effect
    constbindTop2 = () => {
      const timeTop = setInterval(() => {
        document.documentElement.scrollTop = scrollTopH.value -= 50
        if (scrollTopH.value <= 0) {
          clearInterval(timeTop)
        }
      }, 10)
  }

二、將文本復制到剪貼板

構建網站時一個非常普遍的需求是能夠通過單擊按鈕將文本復制到剪貼板。以下這段代碼是一個很通用的代碼,適合大多數瀏覽器。

const copyText = (text) => {
        const clipboardStr = window.clipboardStr
        if (clipboardStr) {
          clipboardStr.clearData()
          clipboardStr.setData('Text', text)
          return true
        } else if (document.execCommand) {  
          //Note: document, execCommand is deprecated but some browsers still support it. Remember to check the compatibility when using it
          // Get the content to be copied by creating a dom element
          const el = document.createElement('textarea')
          el.value = text
          el.setAttribute('readonly', '')
          el.style.position = 'absolute'
          el.style.left = '-9999px'
          document.body.appendChild(el)
          el.select()
          // Copy the current content to the clipboard
          document.execCommand('copy')
          // delete el node
          document.body.removeChild(el)
          return true
        }
        return false
    }

三、防抖/節流

在前端開發的過程中,我們會遇到很多按鈕被頻繁點擊,然后觸發多個事件,但是我們又不想觸發事件太頻繁。這里有兩種常見的解決方案來防止 Debouncing 和 Throttling。

基本介紹

防抖:在指定時間內頻繁觸發事件,以最后一次觸發為準。

節流:一個事件在指定時間內被頻繁觸發,并且只會被觸發一次,以第一次為準。

應用場景

防抖: 輸入搜索,當用戶不斷輸入內容時,使用防抖來減少請求次數,節省請求資源。

節流:場景一般是按鈕點擊。一秒內點擊 10 次將發起 10 個請求。節流后,1秒內點擊多次,只會觸發一次。

// Debouncing
    // fn is the function that needs anti-shake, delay is the timer time
    function debounce(fn,delay){
        let timer = null;
        return function () { 
            //if the timer exists, clear the timer and restart the timer
            if(timer){
                clearTimeout(timeout);
            }
            //Set a timer and execute the actual function to be executed after a specified time
            timeout = setTimeout(() => {
               fn.apply(this);
            }, delay);
        }
    }
    
    // Throttling
    function throttle(fn) {
      let timer = null; // First set a variable, when the timer is not executed, the default is null
      return function () {
        if (timer) return; // When the timer is not executed, the timer is always false, and there is no need to execute it later
        timer = setTimeout(() => {
          fn.apply(this, arguments);
           // Finally, set the flag to true after setTimeout is executed
           // Indicates that the next cycle can be executed.
          timer = null;
        }, 1000);
      };
    }

四、初始化數組

fill() :這是 ES6 中的一個新方法。用指定的元素填充數組,實際上就是用默認的內容初始化數組。

const arrList = Array(6).fill()
   console.log(arrList)  // result:  ['','','','','','']

五、檢查它是否是一個函數

檢測是否是函數 其實寫完后直接寫isFunction就好了,這樣可以避免重復寫判斷。

const isFunction = (obj) => {
        return typeof obj === "function" &&
          typeof obj.nodeType !== "number" && 
          typeof obj.item !== "function";

六、檢查它是否是一個安全數組

檢查它是否是一個安全數組,如果不是,用 isArray 方法在這里返回一個空數組。

const safeArray = (array) => {
    return Array.isArray(array) ? array : []
}

七、檢查對象是否是安全對象

// Check whether the current object is a valid object.
    const isVaildObject = (obj) => {
        return typeof obj === 'object' && 
          !Array.isArray(obj) && Object.keys(obj).length
    }
    const safeObject = obj => isVaildObject(obj) ? obj : {}

八、過濾特殊字符

js中使用正則表達式過濾特殊字符,檢查所有輸入字段是否包含特殊字符。

function filterCharacter(str){
        let pattern = new RegExp("[`~!@#$^&*()=:”“'。,、?|{}':;'%,\\[\\].<>/?~!@#¥……&*()&;—|{ }【】‘;]")
        let resultStr = "";
        for (let i = 0; i < str.length; i++) {
            resultStr = resultStr + str.substr(i, 1).replace(pattern, '');
        }
        return resultStr;
    }
    
  
    filterCharacter('gyaskjdhy12316789#$%^&!@#1=123,./[') 
// result: gyaskjdhy123167891123

結束

今天的分享就到這里,這8個方法你學會了嗎,我強烈建議大家收藏起來,別再造輪子了。希望今天的分享能夠幫助到你,感謝你的閱讀。

責任編輯:姜華 來源: 今日頭條
相關推薦

2020-05-13 21:09:10

JavaScript前端技術

2024-01-11 09:21:13

JavaScript工具JSON

2020-09-16 11:10:33

Linux命令文件

2019-08-07 16:50:38

SQLjoingroup

2022-12-13 08:23:25

CSS前端漸變

2023-11-22 18:04:50

快捷鍵? macOS

2024-01-31 08:47:05

JavaScript工具函數JS

2023-02-22 19:15:35

AI工具機器人

2023-11-26 17:47:00

數據分析

2017-11-21 15:34:15

Linux 開發開源

2024-04-28 11:22:18

2021-08-28 11:47:52

json解析

2021-10-27 17:57:35

設計模式場景

2022-10-10 09:00:35

ReactJSX組件

2011-06-03 17:50:58

2025-04-23 08:20:00

Linux性能監測命令

2021-09-23 15:13:02

Spring依賴Java

2024-12-11 08:20:57

設計模式源碼

2020-12-16 08:33:57

JS函數效率

2018-11-19 15:06:23

Python算法
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 成人av一区二区亚洲精 | 日韩精品在线观看网站 | 亚洲美女视频 | 五月激情六月婷婷 | 无码日韩精品一区二区免费 | 中文字幕一区二区不卡 | 91免费在线看 | 午夜电影网 | 色综合久久88色综合天天 | 国产精品一区二区久久 | 爽爽免费视频 | 一级毛片视频在线 | 国产福利免费视频 | 精品国产99 | 99亚洲精品 | 日本亚洲精品 | 久久综合九色综合欧美狠狠 | 四虎永久免费在线 | 日韩毛片网 | 国产精品视频一二三区 | 国产精品国产成人国产三级 | 成人在线观看网站 | 精品久久久久久亚洲国产800 | 欧美久久久久久 | 一级高清 | 成人福利视频网站 | 国产精品精品久久久久久 | 国产精品久久久久久吹潮 | 欧美精品网 | 国产精品中文 | 欧美精品久久一区 | 久久久国产一区 | 亚洲色图婷婷 | 欧美日韩精品免费 | 福利网站在线观看 | 一级aaaa毛片 | 国产精品视频一二三区 | 日韩视频精品在线 | 福利视频大全 | 午夜精品久久 | 在线精品国产 |