防抖函数
介绍
在短时间内多次触发,只执行一次。一般用于搜索框,输入框等场景。
1 2 3 4 5 6 7 8 9
| const debounce = (callback, delay) => { let timer = null; return (...args)=>{ clearTimeout(timer); timer = setTimeout(()=>{ callback.apply(null,args) }, delay) } }
|
使用
1 2 3 4 5 6
| const handle = debounce((e)=>{ console.log(e); }, 500) window.addEventListener('mousemove', ()=>{ handle("防抖") })
|
节流函数
介绍
在固定时间内只执行一次。一般用于滚动事件等场景。
1 2 3 4 5 6 7 8 9 10 11
| const throttle = (callback, delay) => { let timer = null; return (...args)=>{ if(!timer){ timer = setTimeout(()=>{ callback.apply(null,args) timer = null; }, delay) } } }
|
使用
1 2 3 4 5 6
| const handle = throttle((e)=>{ console.log(e); }) window.addEventListener('scroll', ()=>{ handle("节流") })
|
生成随机数
介绍
给定一个最大值和最小值,类型为整数,生成这个区间的随机数,且为整数。
1 2 3
| const getRandom = (min, max) => { return Math.floor(Math.random() * (max - min) + min); }
|
使用
1 2
| const num = getRandom(1, 10); console.log(num);
|
网页全屏
介绍
操作网页的全屏,浏览器直接提供了接口 requestFullscreen() 和 exitFullscreen(),我们唯一需要注意就是解决一些边缘问题,例如浏览器的兼容,解决全屏背景色等问题。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| function requestFullscreen(doc) { if (doc.mozRequestFullScreen) { doc.mozRequestFullScreen(); } else if (doc.webkitRequestFullScreen) { doc.webkitRequestFullScreen(); } else if (doc.msRequestFullscreen) { doc.msRequestFullscreen(); } else { doc.requestFullscreen(); } } function exitFullScreen() { if (document.mozCancelFullScreen) { document.mozCancelFullScreen(); }else if (document.webkitCancelFullScreen) { document.webkitCancelFullScreen(); } else if (document.msExitFullscreen) { document.msExitFullscreen(); } else { document.exitFullscreen(); } } function addFullscreenchangeListener(doc, callback) { doc.addEventListener('fullscreenchange', callback); doc.addEventListener('mozfullscreenchange', callback); doc.addEventListener('webkitfullscreenchange', callback); doc.addEventListener('msfullscreenchange', callback); } function removeFullscreenchangeListener(doc, callback) { doc.removeEventListener('fullscreenchange', callback); doc.removeEventListener('mozfullscreenchange', callback); doc.removeEventListener('webkitfullscreenchange', callback); doc.removeEventListener('msfullscreenchange', callback); }
|
1 2 3
| :not(:root):fullscreen::backdrop{ background-color: #fff; }
|
使用
1 2 3 4 5 6
| addFullscreenchangeListener(document.body, ()=>{ console.log("全屏状态改变"); }) document.body.addEventListener('click', ()=>{ requestFullscreen(document.body); })
|