在实际开发项目中,我们会遇到很多重复的需求,为了提升工作效率,我们常常会整理很多属于自己的常用工具和功能模块代码,必要的时候,我们会将其进行迭代更新。
今天这篇文章,我们要跟大家分享的就是一些关于JavaScrpt的常用方法的整理,希望这些方法能够帮助到你。
1、实现全屏
functionfullScreen() {const el = document.documentElementconst rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.mozRequestFullScreen || el.msRequestFullscreenif(typeof rfs != "undefined" && rfs) { rfs.call(el) }}fullScreen()
2、退出全屏
functionexitScreen() {if (document.exitFullscreen) { document.exitFullscreen() } elseif (document.mozCancelFullScreen) { document.mozCancelFullScreen() } elseif (document.webkitCancelFullScreen) { document.webkitCancelFullScreen() } elseif (document.msExitFullscreen) { document.msExitFullscreen() } if(typeof cfs != "undefined" && cfs) { cfs.call(el) }}exitScreen()
3、页面打印
window.print()
4、打印内容样式更改
<style>/* 使用@media print可以调整你需要的打印样式 */@media print {.noprint {display: none; }}</style><divclass="print">print</div><divclass="noprint">noprint</div>
5、阻止关闭事件
//当你需要防止用户刷新或者关闭浏览器,你可以选择触发 beforeunload 事件,部分浏览器不能自定义文本内容window.onbeforeunload = function(){return'您确定要离开haorooms博客吗?';};
6、屏幕录制
//当你需要将录制当前屏幕,并将录屏上传或下载const streamPromise = navigator.mediaDevices.getDisplayMedia()streamPromise.then(stream => {var recordedChunks = [];// 录制的视频数据var options = { mimeType: "video/webm; codecs=vp9" };// 设置编码格式var mediaRecorder = newMediaRecorder(stream, options);// 初始化MediaRecorder实例 mediaRecorder.ondataavailable = handleDataAvailable;// 设置数据可用(录屏结束)时的回调 mediaRecorder.start();// 视频碎片合并functionhandleDataAvailable(event) {if (event.data.size > 0) { recordedChunks.push(event.data);// 添加数据,event.data是一个BLOB对象download();// 封装成BLOB对象并下载 } }// 文件下载functiondownload() {var blob = newBlob(recordedChunks, {type: "video/webm" });// 此处可将视频上传到后端var url = URL.createObjectURL(blob);var a = document.createElement("a");document.body.appendChild(a); a.style = "display: none"; a.href = url; a.download = "test.webm"; a.click();window.URL.revokeObjectURL(url); }})
7、判断横竖屏
functionhengshuping(){if(window.orientation==180||window.orientation==0){alert("竖屏状态!") }if(window.orientation==90||window.orientation==-90){alert("横屏状态!") }}window.addEventListener("onorientationchange"inwindow ? "orientationchange" : "resize", hengshuping, false);
8、横竖屏样式变更
<style>@media all and (orientation : landscape) {body {background-color: #ff0000; }}@media all and (orientation : portrait) {body {background-color: #00ff00; }}</style>
9、标签页显隐
//当你需要对标签页显示隐藏进行事件监听时const {hidden, visibilityChange} = (() => {let hidden, visibilityChange;if (typeofdocument.hidden !== "undefined") {// Opera 12.10 and Firefox 18 and later support hidden = "hidden"; visibilityChange = "visibilitychange"; } elseif (typeofdocument.msHidden !== "undefined") { hidden = "msHidden"; visibilityChange = "msvisibilitychange"; } elseif (typeofdocument.webkitHidden !== "undefined") { hidden = "webkitHidden"; visibilityChange = "webkitvisibilitychange"; }return { hidden, visibilityChange }})();consthandleVisibilityChange = () => {console.log("当前被隐藏", document[hidden]);};document.addEventListener( visibilityChange, handleVisibilityChange,false);
10、本地图片预览
//当你从客户端获取到一张图片但不能立刻上传到服务器,却需要预览的时候<div class="test"><inputtype="file"name=""id=""><imgsrc=""alt=""></div><script>constgetObjectURL = (file) => {let url = null;if (window.createObjectURL != undefined) { // basic url = window.createObjectURL(file); } elseif (window.URL != undefined) { // webkit or chrome url = window.URL.createObjectURL(file); } elseif (window.URL != undefined) { // mozilla(firefox) url = window.URL.createObjectURL(file); }return url;}document.querySelector('input').addEventListener('change', (event) => {document.querySelector('img').src = getObjectURL(event.target.files[0])})</script>
11、图片预加载
//当你有大量图片的时候,你需要将图片进行预加载以免出现白屏的情况const images = []function preloader(args) {for (let i = 0, len = args.length; i < len; i++) { images[i] = new Image() images[i].src = args[i] }}preloader(['1.png', '2.jpg'])
12、字符串脚本化
//当你需要将一串字符串转换成一个 js 脚本,该方法有 xss 漏洞,慎用const obj = eval('({ name: "jack" })')// obj会被转换为对象{ name: "jack" }const v = eval('obj')// v会变成obj这个变量
13、递归函数名解耦
//当你需要写一个递归函数的时候,你声明了一个函数名,但是每次修改函数名的时候总会忘记修改内部的函数名。argument 为函数内部对象,包含传入函数的所有参数,arguments.callee 代表函数名。// 这是一个最基础的斐波那契数列functionfibonacci (n) {constfn = arguments.calleeif (n <= 1) return1returnfn(n - 1) + fn(n - 2)}
14、隐显判断
//当你需要对一个 dom 元素进行判断当前是否出现在页面视图内,你可以尝试用 IntersectionObserver 进行判断<style>.item {height: 350px;}</style><divclass="container"><divclass="item"data-id="1">不可见</div><divclass="item"data-id="2">不可见</div><divclass="item"data-id="3">不可见</div></div><script>if (window?.IntersectionObserver) {let items = [...document.getElementsByClassName("item")]; // 解析为真数组,也可用 Array.prototype.slice.call()let io = newIntersectionObserver((entries) => { entries.forEach((item) => { item.target.innerHTML = item.intersectionRatio === 1// 元素显示比例,为1时完全可见,为0时完全不可见 ? 元素完全可见 : 元素部分不可见; }); }, {root: null,rootMargin: "0px 0px",threshold: 1, // 阀值设为1,当只有比例达到1时才触发回调函数 } ); items.forEach((item) => io.observe(item)); }</script>
15、元素可编辑
//当你需要在某个 dom 元素进行编辑,让它点击的时候就像一个 textarea<divcontenteditable="true">这里是可编辑的内容</div>
16、元素属性监听
<divid="test">test</div><buttononclick="handleClick()">OK</button><script>const el = document.getElementById("test");let n = 1;const observe = newMutationObserver((mutations) => {console.log("属性发生变化了", mutations); }) observe.observe(el, {attributes: true });functionhandleClick() { el.setAttribute("style", "color: red"); el.setAttribute("data-name", n++); }setTimeout(() => { observe.disconnect(); // 停止监听 }, 5000);</script>
17、打印 dom 元素
//当你需要在开发过程中打印 dom 元素时,使用 console.log 往往只会打印出整个 dom 元素,而无法查看该 dom 元素的内部属性。你可以尝试使用 console.dirconsole.dir(document.body)
18、激活应用
//当你在移动端开发时,需要打开其他应用。以下方法也可以通过 location.href 赋值操作<ahref="tel:12345678910">电话</a><ahref="sms:12345678910,12345678911?body=你好">android短信</a><ahref="sms:/open?addresses=12345678910,12345678911&body=你好">ios短信</a><ahref="wx://">ios短信</a>
以上就是我们在开发中,会经常使用的18个开发方法,希望这些方法能够帮助到你。
最后,感谢你的阅读,祝编程愉快!