日韩成人免费在线_国产成人一二_精品国产免费人成电影在线观..._日本一区二区三区久久久久久久久不

當前位置:首頁 > 科技  > 軟件

18 個高級工程師必須會的強大JavaScript 技巧

來源: 責編: 時間:2023-08-14 22:01:28 360觀看
導讀瀏覽器01、實現全屏當您需要將當前屏幕顯示為全屏時function fullScreen() { const el = document.documentElement const rfs = el.requestFullScreen || el.webkitRequestFullScreen || el.moz

瀏覽器

YTv28資訊網——每日最新資訊28at.com

01、實現全屏當您需要將當前屏幕顯示為全屏時

function fullScreen() {      const el = document.documentElement    const rfs =     el.requestFullScreen ||     el.webkitRequestFullScreen ||     el.mozRequestFullScreen ||     el.msRequestFullscreen    if(typeof rfs != "undefined" && rfs) {        rfs.call(el)    }}fullScreen()

02、退出全屏

當您需要退出全屏時YTv28資訊網——每日最新資訊28at.com

function exitScreen() {    if (document.exitFullscreen) {         document.exitFullscreen()    }     else if (document.mozCancelFullScreen) {         document.mozCancelFullScreen()    }     else if (document.webkitCancelFullScreen) {         document.webkitCancelFullScreen()    }     else if (document.msExitFullscreen) {         document.msExitFullscreen()    }     if(typeof cfs != "undefined" && cfs) {        cfs.call(el)    }}exitScreen()

03、頁面打印

當您需要打印當前頁面時YTv28資訊網——每日最新資訊28at.com

window.print()

04、打印內容風格變更

當需要打印出當前頁面,但需要修改當前布局時YTv28資訊網——每日最新資訊28at.com

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

05、阻止關閉事件

當需要阻止用戶刷新或關閉瀏覽器時,可以選擇觸發beforeunload事件,有些瀏覽器無法自定義文本內容YTv28資訊網——每日最新資訊28at.com

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

06、屏幕錄制

當您需要錄制當前屏幕并上傳或下載屏幕錄制時YTv28資訊網——每日最新資訊28at.com

const streamPromise = navigator.mediaDevices.getDisplayMedia()streamPromise.then(stream => {    var recordedChunks = [];// recorded video datavar options = { mimeType: "video/webm; codecs=vp9" };// Set the encoding format    var mediaRecorder = new MediaRecorder(stream, options);// Initialize the MediaRecorder instance    mediaRecorder.ondataavailable = handleDataAvailable;// Set the callback when data is available (end of screen recording)    mediaRecorder.start();    // Video Fragmentation    function handleDataAvailable(event) {        if (event.data.size > 0) {            recordedChunks.push(event.data);// Add data, event.data is a BLOB object            download();// Encapsulate into a BLOB object and download        }    }// file download    function download() {        var blob = new Blob(recordedChunks, {            type: "video/webm"        });        // Videos can be uploaded to the backend here        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);    }})

07、判斷橫屏和豎屏

當您需要判斷手機橫屏或豎屏狀態時YTv28資訊網——每日最新資訊28at.com

const streamPromise = navigator.mediaDevices.getDisplayMedia()streamPromise.then(stream => {    var recordedChunks = [];// recorded video datavar options = { mimeType: "video/webm; codecs=vp9" };// Set the encoding format    var mediaRecorder = new MediaRecorder(stream, options);// Initialize the MediaRecorder instance    mediaRecorder.ondataavailable = handleDataAvailable;// Set the callback when data is available (end of screen recording)    mediaRecorder.start();    // Video Fragmentation    function handleDataAvailable(event) {        if (event.data.size > 0) {            recordedChunks.push(event.data);// Add data, event.data is a BLOB object            download();// Encapsulate into a BLOB object and download        }    }// file download    function download() {        var blob = new Blob(recordedChunks, {            type: "video/webm"        });        // Videos can be uploaded to the backend here        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);    }})

08、改變橫豎屏樣式

當你需要為橫豎屏設置不同的樣式時YTv28資訊網——每日最新資訊28at.com

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

09、標簽頁隱藏

當需要監聽tab顯示和隱藏事件時YTv28資訊網——每日最新資訊28at.com

const {hidden, visibilityChange} = (() => {    let hidden, visibilityChange;    if (typeof document.hidden !== "undefined") {      // Opera 12.10 and Firefox 18 and later support      hidden = "hidden";      visibilityChange = "visibilitychange";    } else if (typeof document.msHidden !== "undefined") {      hidden = "msHidden";      visibilityChange = "msvisibilitychange";    } else if (typeof document.webkitHidden !== "undefined") {      hidden = "webkitHidden";      visibilityChange = "webkitvisibilitychange";    }    return {      hidden,      visibilityChange    }})();const handleVisibilityChange = () => {    console.log("currently hidden", document[hidden]);};document.addEventListener(    visibilityChange,    handleVisibilityChange,    false);

圖片YTv28資訊網——每日最新資訊28at.com

10、本地圖片預覽

當您從客戶端獲取圖片但無法立即上傳到服務器,但需要預覽時YTv28資訊網——每日最新資訊28at.com

<class="test">    <input type="file" name="" id="">    <img src="" alt=""></div><script>const getObjectURL = (file) => {    let url = null;    if (window.createObjectURL != undefined) { // basic        url = window.createObjectURL(file);    } else if (window.URL != undefined) { // webkit or chrome        url = window.URL.createObjectURL(file);    } else if (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>

YTv28資訊網——每日最新資訊28at.com

11、圖片預加載

當圖片較多時,需要預加載圖片以避免白屏YTv28資訊網——每日最新資訊28at.com

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'])

JavaScriptYTv28資訊網——每日最新資訊28at.com

12、字符串腳本

當需要將一串字符串轉換為JavaScript腳本時,該方法存在xss漏洞,請謹慎使用YTv28資訊網——每日最新資訊28at.com

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

13、遞歸函數名解耦

當需要編寫遞歸函數時,聲明了函數名,但是每次修改函數名時,總是忘記修改內部函數名。argument是函數的內部對象,包括傳入函數的所有參數,arguments.callee代表函數名。YTv28資訊網——每日最新資訊28at.com

// This is a basic Fibonacci sequencefunction fibonacci (n) {    const fn = arguments.callee    if (n <= 1) return 1    return fn(n - 1) + fn(n - 2)}

DOM 元素YTv28資訊網——每日最新資訊28at.com

14、隱性判斷

當需要判斷某個dom元素當前是否出現在頁面視圖中時,可以嘗試使用IntersectionObserver來判斷。YTv28資訊網——每日最新資訊28at.com

<style>.item {    height: 350px;}</style><class="container">  <class="item" data-id="1">Invisible</div>  <class="item" data-id="2">Invisible</div>  <class="item" data-id="3">Invisible</div></div><script>  if (window?.IntersectionObserver) {    let items = [...document.getElementsByClassName("item")]; // parses as a true array, also available Array.prototype.slice.call()let io = new IntersectionObserver(      (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元素時,讓它像文本區域一樣點擊。YTv28資訊網——每日最新資訊28at.com

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

16、元素屬性監控

<id="test">test</div><button onclick="handleClick()">OK</button><script>  const el = document.getElementById("test");  let n = 1;  const observe = new MutationObserver((mutations) => {    console.log("attribute is changede", mutations);  })  observe.observe(el, {    attributes: true  });  function handleClick() {    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.dirYTv28資訊網——每日最新資訊28at.com

console.dir(document.body)

其他YTv28資訊網——每日最新資訊28at.com

18、激活應用程序

當你在移動端開發時,你需要打開其他應用程序。還可以通過location.href賦值來操作以下方法YTv28資訊網——每日最新資訊28at.com

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

總結

以上就是我今天想與你分享的全部內容,希望對你有所幫助,最后,感謝你的閱讀,祝編程愉快!YTv28資訊網——每日最新資訊28at.com

本文鏈接:http://www.www897cc.com/showinfo-26-5744-0.html18 個高級工程師必須會的強大JavaScript 技巧

聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。郵件:2376512515@qq.com

上一篇: 新興技術趨勢將徹底改變我們的世界

下一篇: SpringCloud Gateway 路由如何定位從底層源碼分析

標簽:
  • 熱門焦點
  • 對標蘋果的靈動島 華為帶來實況窗功能

    繼蘋果的靈動島之后,華為也在今天正式推出了“實況窗”功能。據今天鴻蒙OS 4.0的現場演示顯示,華為的實況窗可以更高效的展現出實時通知,比如鎖屏上就能看到外賣、打車、銀行
  • 5月iOS設備性能榜:M1 M2依舊是榜單前五

    和上個月一樣,沒有新品發布的iOS設備性能榜的上榜設備并沒有什么更替,僅僅只有跑分變化而產生的排名變動,剛剛開始的蘋果WWDC2023,推出的產品也依舊是新款Mac Pro、新款Mac Stu
  • K6:面向開發人員的現代負載測試工具

    K6 是一個開源負載測試工具,可以輕松編寫、運行和分析性能測試。它建立在 Go 和 JavaScript 之上,它被設計為功能強大、可擴展且易于使用。k6 可用于測試各種應用程序,包括 Web
  • SpringBoot中使用Cache提升接口性能詳解

    環境:springboot2.3.12.RELEASE + JSR107 + Ehcache + JPASpring 框架從 3.1 開始,對 Spring 應用程序提供了透明式添加緩存的支持。和事務支持一樣,抽象緩存允許一致地使用各
  • 分布式系統中的CAP理論,面試必問,你理解了嘛?

    對于剛剛接觸分布式系統的小伙伴們來說,一提起分布式系統,就感覺高大上,深不可測。而且看了很多書和視頻還是一臉懵逼。這篇文章主要使用大白話的方式,帶你理解一下分布式系統
  • .NET 程序的 GDI 句柄泄露的再反思

    一、背景1. 講故事上個月我寫過一篇 如何洞察 C# 程序的 GDI 句柄泄露 文章,當時用的是 GDIView + WinDbg 把問題搞定,前者用來定位泄露資源,后者用來定位泄露代碼,后面有朋友反
  • 本地生活這塊肥肉,拼多多也想吃一口

    出品/壹覽商業 作者/李彥編輯/木魚拼多多也看上本地生活這塊蛋糕了。近期,拼多多在App首頁&ldquo;充值中心&rdquo;入口上線了本機生活界面。壹覽商業發現,該界面目前主要
  • 大廠卷向扁平化

    來源:新熵作者丨南枝 編輯丨月見大廠職級不香了。俗話說,兵無常勢,水無常形,互聯網企業調整職級體系并不稀奇。7月13日,淘寶天貓集團啟動了近年來最大的人力制度改革,目前已形成一
  • 電博會上海爾智家模擬500平大平層,還原生活空間沉浸式體驗

    電博會為了更好地讓參展觀眾真正感受到智能家居的絕妙之處,海爾智家的程傳嶺先生同樣介紹了展會上海爾智家的模擬500平大平層,還原生活空間沉浸式體驗。程傳
Top 主站蜘蛛池模板: 嘉黎县| 武冈市| 乌鲁木齐县| 乌审旗| 南澳县| 台北县| 沛县| 平谷区| 衡水市| 阳朔县| 眉山市| 阿城市| 宁阳县| 通州市| 沙田区| 化州市| 桓仁| 佛坪县| 西乌珠穆沁旗| 武城县| 读书| 榕江县| 浦江县| 定西市| 林芝县| 南郑县| 金堂县| 新疆| 正阳县| 上虞市| 连山| 白城市| 兴山县| 三门峡市| 开原市| 上饶县| 栾川县| 丹巴县| 贺兰县| 讷河市| 巩留县|