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

开发 前端
今天我们一起来聊一聊18 个高级工程师必须会的强大JavaScript 技巧都有哪些吧。

浏览器

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、退出全屏

当您需要退出全屏时

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、页面打印

当您需要打印当前页面时

window.print()

04、打印内容风格变更

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

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

05、阻止关闭事件

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

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

06、屏幕录制

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

const streamPromise = navigator.mediaDevices.getDisplayMedia()
streamPromise.then(stream => {
    var recordedChunks = [];// recorded video data
var 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、判断横屏和竖屏

当您需要判断手机横屏或竖屏状态时

const streamPromise = navigator.mediaDevices.getDisplayMedia()
streamPromise.then(stream => {
    var recordedChunks = [];// recorded video data
var 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、改变横竖屏样式

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

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

09、标签页隐藏

当需要监听tab显示和隐藏事件时

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

图片

10、本地图片预览

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

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

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

JavaScript

12、字符串脚本

当需要将一串字符串转换为JavaScript脚本时,该方法存在xss漏洞,请谨慎使用

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代表函数名。

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

DOM 元素

14、隐性判断

当需要判断某个dom元素当前是否出现在页面视图中时,可以尝试使用IntersectionObserver来判断。

<style>
.item {
    height: 350px;
}
</style>

<div class="container">
  <div class="item" data-id="1">Invisible</div>
  <div class="item" data-id="2">Invisible</div>
  <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元素时,让它像文本区域一样点击。

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

16、元素属性监控

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

总结

以上就是我今天想与你分享的全部内容,希望对你有所帮助,最后,感谢你的阅读,祝编程愉快!

责任编辑:华轩 来源: web前端开发
相关推荐

2023-05-29 16:09:22

JavaScript技能浏览器

2022-08-23 08:00:00

高级工程师软件工程师代码库

2020-12-18 11:55:27

编程面试

2015-05-11 09:38:42

.NET高级工程师面试题

2018-09-20 10:55:38

数据库顺丰高级工程师

2019-09-20 21:30:32

前端工程师JavaScript

2010-12-24 10:47:48

网络规划设计师

2011-01-04 11:48:04

系统分析师

2010-12-24 10:50:43

系统架构设计师

2012-04-23 09:21:11

NetflixAmazonQCon

2010-12-29 11:15:51

信息系统项目管理师

2020-12-07 08:01:59

JavaScript入门技巧

2019-12-20 14:32:55

JavaScript函数开发

2018-09-21 16:30:55

2020-12-23 08:03:01

JavaScript开发代码

2009-04-16 09:47:29

2015-08-14 09:45:10

Webnode.jsH5

2023-12-27 14:12:40

JavaScrip技巧

2020-07-22 14:50:35

Python数据分析
点赞
收藏

51CTO技术栈公众号