一、回到顶部
当页面很长时,如果用户想回到页面顶部,必须滚动滚动键几次才能回到顶部。如果页面右下角有“返回顶部”按钮,用户可以点击返回顶部。对于用户来说,这是一个很好的用户体验。
// Method 1constbindTop1 = () => {window.scrollTo(0, 0)document.documentElement.scrollTop = 0;}// Method 2: Scrolling through the timer will be visually smoother, without much lag effectconstbindTop2 = () => {const timeTop = setInterval(() => {document.documentElement.scrollTop = scrollTopH.value -= 50if (scrollTopH.value <= 0) {clearInterval(timeTop)}}, 10)}
二、将文本复制到剪贴板
构建网站时一个非常普遍的需求是能够通过单击按钮将文本复制到剪贴板。以下这段代码是一个很通用的代码,适合大多数浏览器。
const copyText = (text) => {const clipboardStr = window.clipboardStrif (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 elementconst el = document.createElement('textarea')el.value = textel.setAttribute('readonly', '')el.style.position = 'absolute'el.style.left = '-9999px'document.body.appendChild(el)el.select()// Copy the current content to the clipboarddocument.execCommand('copy')// delete el nodedocument.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 timefunction debounce(fn,delay){let timer = null;return function () { //if the timer exists, clear the timer and restart the timerif(timer){clearTimeout(timeout);}//Set a timer and execute the actual function to be executed after a specified timetimeout = setTimeout(() => {fn.apply(this);}, delay);}}// Throttlingfunction throttle(fn) {let timer = null; // First set a variable, when the timer is not executed, the default is nullreturn function () {if (timer) return; // When the timer is not executed, the timer is always false, and there is no need to execute it latertimer = 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个方法你学会了吗,我强烈建议大家收藏起来,别再造轮子了。希望今天的分享能够帮助到你,感谢你的阅读。