18 个强大的高级工程师必会JavaScript 技能

今天一起来了解下强大的高级工程师必会JavaScript 技能都有哪些吧!
首页 新闻资讯 行业资讯 18 个强大的高级工程师必会JavaScript 技能

浏览器

d5da91b034a964847548743d78e36ca962db78.jpg

1.实现全屏

当你需要将当前屏幕显示为全屏时

functionfullScreen(){constel=document.documentElementconstrfs=el.requestFullScreen||el.webkitRequestFullScreen||el.mozRequestFullScreen||el.msRequestFullscreenif(typeofrfs!="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(typeofcfs!="undefined"&&cfs){cfs.call(el)}}exitScreen()

3.页面打印

当您需要打印当前页面时

window.print()

4.打印内容样式改变

当需要打印出当前页面,但又需要修改当前布局时

<style>/* Use @media print to adjust the print style you need */@media print{.noprint{display:none;}}</style><divclass="print">print</div><divclass="noprint">noprint</div>

5.阻止关闭事件

当需要阻止用户刷新或关闭浏览器时,可以选择触发beforeunload事件,部分浏览器无法自定义文本内容。

window.onbeforeunload=function(){return'Are you sure you want to leave the haorooms blog?';};

6.屏幕录制

当您需要录制当前屏幕并上传或下载屏幕录像时

conststreamPromise=navigator.mediaDevices.getDisplayMedia()streamPromise.then(stream=>{varrecordedChunks=[];// recorded video datavaroptions={mimeType:"video/webm; codecs=vp9"};// Set the encoding formatvarmediaRecorder=newMediaRecorder(stream,options);// Initialize the MediaRecorder instancemediaRecorder.ondataavailable=handleDataAvailable;// Set the callback when data is available (end of screen recording)mediaRecorder.start();// Video FragmentationfunctionhandleDataAvailable(event){if(event.data.size>0){recordedChunks.push(event.data);// Add data, event.data is a BLOB objectdownload();// Encapsulate into a BLOB object and download}}// file downloadfunctiondownload(){varblob=newBlob(recordedChunks,{type:"video/webm"});// Videos can be uploaded to the backend herevarurl=URL.createObjectURL(blob);vara=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("Portrait state!")}if(window.orientation==90||window.orientation==-90){alert("Landscape state!")}}window.addEventListener("onorientationchange"inwindow?"orientationchange":"resize",hengshuping,false);

8.改变横竖屏的样式

当你需要为横竖屏设置不同的样式时

<style>@media alland(orientation:landscape){body{background-color:#ff0000;}}@media alland(orientation:portrait){body{background-color:#00ff00;}}</style>

9.标签页隐藏

当你需要监听标签显示和隐藏的事件时

const{hidden,visibilityChange}=(()=>{lethidden,visibilityChange;if(typeofdocument.hidden!=="undefined"){// Opera 12.10 and Firefox 18 and later supporthidden="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("currently hidden",document[hidden]);};document.addEventListener(visibilityChange,handleVisibilityChange,false);

图片

10.本地图片预览

当你从客户端获取图片但不能立即上传到服务器,需要预览时

<divclass="test"><input type="file"name=""id=""><img src=""alt=""></div><script>constgetObjectURL=(file)=>{leturl=null;if(window.createObjectURL!=undefined){// basicurl=window.createObjectURL(file);}elseif(window.URL!=undefined){// webkit or chromeurl=window.URL.createObjectURL(file);}elseif(window.URL!=undefined){// mozilla(firefox)url=window.URL.createObjectURL(file);}returnurl;}document.querySelector('input').addEventListener('change',(event)=>{document.querySelector('img').src=getObjectURL(event.target.files[0])})</script>

11.图片预加载

当你有很多图片时,你需要预加载图片以避免白屏

constimages=[]functionpreloader(args){for(leti=0,len=args.length;i<len;i++){images[i]=newImage()images[i].src=args[i]}}preloader(['1.png','2.jpg'])

JavaScript

12.字符串脚本

当需要将一串字符串转成js脚本时,该方法存在xss漏洞,慎用

constobj=eval('({ name: "jack" })')// obj will be converted to object{ name: "jack" }constv=eval('obj')// v will become the variable obj

13.递归函数名解耦

当你需要写一个递归函数时,你声明了一个函数名,但是每次修改函数名时,你总是忘记修改内部函数名。argument是函数的内部对象,包括传入函数的所有参数,arguments.callee代表函数名。

// This is a basic Fibonacci sequencefunctionfibonacci(n){constfn=arguments.calleeif(n<=1)return1returnfn(n-1)+fn(n-2)}

DOM 元素

14.隐性判断

当需要判断一个dom元素当前是否出现在page view中时,可以尝试使用IntersectionObserver来判断。

<style>.item{height:350px;}</style><divclass="container"><divclass="item"data-id="1">Invisible</div><divclass="item"data-id="2">Invisible</div><divclass="item"data-id="3">Invisible</div></div><script>if(window?.IntersectionObserver){letitems=[...document.getElementsByClassName("item")];// parses as a true array, also available Array.prototype.slice.call()letio=newIntersectionObserver((entries)=>{entries.forEach((item)=>{item.target.innerHTML=item.intersectionRatio===1// The display ratio of the element, when it is 1, it is completely visible, and when it is 0, it is completely invisible?`Element is fully visible`:`Element is partially invisible`;});},{root:null,rootMargin:"0px 0px",threshold:1,// The threshold is set to 1, and the callback function is triggered only when the ratio reaches 1});items.forEach((item)=>io.observe(item));}</script>

15.元素可编辑

当你需要编辑一个dom元素时,让它像textarea一样点击

<div contenteditable="true">here can be edited</div>

16.元素属性监控

<div id="test">test</div><button onclick="handleClick()">OK</button><script>constel=document.getElementById("test");letn=1;constobserve=newMutationObserver((mutations)=>{console.log("attribute is changede",mutations);})observe.observe(el,{attributes:true});functionhandleClick(){el.setAttribute("style","color: red");el.setAttribute("data-name",n++);}setTimeout(()=>{observe.disconnect();// stop watch},5000);</script>

17.打印dom元素

在开发过程中需要打印dom元素时,使用console.log往往只能打印出整个dom元素,无法查看dom元素的内部属性。您可以尝试使用 console.dir

console.dir(document.body)

其他

18.激活应用

当你在移动端开发时,你需要打开其他应用程序。location.href赋值也可以操作以下方法。

<a href="tel:12345678910">phone</a><a href="sms:12345678910,12345678911?body=hello">android message</a><a href="sms:/open?addresses=12345678910,12345678911&body=hello">ios message</a><a href="wx://">ios message</a>

总结

以上就是今天与你分享的18个JavaScript技巧。