日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

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

來源: 責編: 時間:2024-01-08 09:17:20 219觀看
導讀一、回到頂部當頁面很長時,如果用戶想回到頁面頂部,必須滾動滾動鍵幾次才能回到頂部。如果頁面右下角有“返回頂部”按鈕,用戶可以點擊返回頂部。對于用戶來說,這是一個很好的用戶體驗。// Method 1 constbindTop1 = ()

OVK28資訊網——每日最新資訊28at.com

一、回到頂部

當頁面很長時,如果用戶想回到頁面頂部,必須滾動滾動鍵幾次才能回到頂部。如果頁面右下角有“返回頂部”按鈕,用戶可以點擊返回頂部。對于用戶來說,這是一個很好的用戶體驗。OVK28資訊網——每日最新資訊28at.com

// 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)  }

二、將文本復制到剪貼板

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

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。OVK28資訊網——每日最新資訊28at.com

基本介紹

防抖:在指定時間內頻繁觸發事件,以最后一次觸發為準。OVK28資訊網——每日最新資訊28at.com

節流:一個事件在指定時間內被頻繁觸發,并且只會被觸發一次,以第一次為準。OVK28資訊網——每日最新資訊28at.com

應用場景

防抖: 輸入搜索,當用戶不斷輸入內容時,使用防抖來減少請求次數,節省請求資源。OVK28資訊網——每日最新資訊28at.com

節流:場景一般是按鈕點擊。一秒內點擊 10 次將發起 10 個請求。節流后,1秒內點擊多次,只會觸發一次。OVK28資訊網——每日最新資訊28at.com

// 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 中的一個新方法。用指定的元素填充數組,實際上就是用默認的內容初始化數組。OVK28資訊網——每日最新資訊28at.com

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

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

檢測是否是函數 其實寫完后直接寫isFunction就好了,這樣可以避免重復寫判斷。OVK28資訊網——每日最新資訊28at.com

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

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

檢查它是否是一個安全數組,如果不是,用 isArray 方法在這里返回一個空數組。OVK28資訊網——每日最新資訊28at.com

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中使用正則表達式過濾特殊字符,檢查所有輸入字段是否包含特殊字符。OVK28資訊網——每日最新資訊28at.com

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個方法你學會了嗎,我強烈建議大家收藏起來,別再造輪子了。希望今天的分享能夠幫助到你,感謝你的閱讀。OVK28資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-57908-0.htmlJS小知識,分享工作中常用的八個封裝函數,讓你事半功倍

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 生產級K8S監控告警方案分享給你

下一篇: 九條微服務最佳實踐,你學會了哪條?

標簽:
  • 熱門焦點
Top 主站蜘蛛池模板: 肥西县| 耒阳市| 资阳市| 来安县| 方城县| 石河子市| 大姚县| 若尔盖县| 邢台市| 渑池县| 来安县| 兴隆县| 沐川县| 海原县| 仪陇县| 天等县| 星子县| 淮南市| 南开区| 屯昌县| 师宗县| 牡丹江市| 宿州市| 中西区| 昂仁县| 揭东县| 格尔木市| 东丽区| 桓台县| 安陆市| 崇义县| 满城县| 友谊县| 达州市| 峨边| 阳泉市| 琼中| 亳州市| 潮州市| 潜山县| 上林县|