JS小知识,分享工作中常用的八个封装函数,让你事半功倍

其他   2024-02-13 09:03   170   0  

一、回到顶部

当页面很长时,如果用户想回到页面顶部,必须滚动滚动键几次才能回到顶部。如果页面右下角有“返回顶部”按钮,用户可以点击返回顶部。对于用户来说,这是一个很好的用户体验。

// 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。

基本介绍

应用场景

// 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个方法你学会了吗,我强烈建议大家收藏起来,别再造轮子了。希望今天的分享能够帮助到你,感谢你的阅读。

博客评论
还没有人评论,赶紧抢个沙发~
发表评论
说明:请文明发言,共建和谐网络,您的个人信息不会被公开显示。
闲言碎语
放心吧,只要你持续走下坡路,就永远不会处在人生最低谷。
赞赏支持

如果觉得博客文章对您有帮助,异或土豪有钱任性,可以通过以下扫码向我捐助。也可以动动手指,帮我分享和传播。您的肯定,是我不懈努力的动力!感谢各位亲~