欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

js常用方法示例梳理(總結(jié)篇)

 更新時間:2023年05月19日 08:53:43   作者:墨城  
這篇文章主要為大家介紹了js常用的方法示例梳理總結(jié)及功能詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪

1、實現(xiàn)全屏

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

2、退出全屏

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

3、頁面打印

window.print()

4、打印內(nèi)容樣式更改

<style>
/* 使用@media print可以調(diào)整你需要的打印樣式 */
@media print {
    .noprint {
        display: none;
    }
}
</style>
<div class="print">print</div>
<div class="noprint">noprint</div>

5、阻止關(guān)閉事件

//當(dāng)你需要防止用戶刷新或者關(guān)閉瀏覽器,你可以選擇觸發(fā) beforeunload 事件,部分瀏覽器不能自定義文本內(nèi)容

window.onbeforeunload = function(){
    return '您確定要離開haorooms博客嗎?';
};

6、屏幕錄制

//當(dāng)你需要將錄制當(dāng)前屏幕,并將錄屏上傳或下載
const streamPromise = navigator.mediaDevices.getDisplayMedia()
streamPromise.then(stream => {
    var recordedChunks = [];// 錄制的視頻數(shù)據(jù)
    var options = { mimeType: "video/webm; codecs=vp9" };// 設(shè)置編碼格式
    var mediaRecorder = new MediaRecorder(stream, options);// 初始化MediaRecorder實例
    mediaRecorder.ondataavailable = handleDataAvailable;// 設(shè)置數(shù)據(jù)可用(錄屏結(jié)束)時的回調(diào)
    mediaRecorder.start();
    // 視頻碎片合并
    function handleDataAvailable(event) {
        if (event.data.size > 0) {
            recordedChunks.push(event.data);// 添加數(shù)據(jù),event.data是一個BLOB對象
            download();// 封裝成BLOB對象并下載
        }
    }
    // 文件下載
    function download() {
        var blob = new Blob(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、判斷橫豎屏

function hengshuping(){
    if(window.orientation==180||window.orientation==0){
        alert("豎屏狀態(tài)!")
    }
    if(window.orientation==90||window.orientation==-90){
        alert("橫屏狀態(tài)!")
    }
}
window.addEventListener("onorientationchange" in window ? "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、標(biāo)簽頁顯隱

//當(dāng)你需要對標(biāo)簽頁顯示隱藏進(jìn)行事件監(jiān)聽時
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("當(dāng)前被隱藏", document[hidden]);
};
document.addEventListener(
    visibilityChange,
    handleVisibilityChange,
    false
);

10、本地圖片預(yù)覽

//當(dāng)你從客戶端獲取到一張圖片但不能立刻上傳到服務(wù)器,卻需要預(yù)覽的時候
<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、圖片預(yù)加載

//當(dāng)你有大量圖片的時候,你需要將圖片進(jìn)行預(yù)加載以免出現(xiàn)白屏的情況
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、字符串腳本化

//當(dāng)你需要將一串字符串轉(zhuǎn)換成一個 js 腳本,該方法有 xss 漏洞,慎用

const obj = eval('({ name: "jack" })')
// obj會被轉(zhuǎn)換為對象{ name: "jack" }
const v = eval('obj')
// v會變成obj這個變量

13、遞歸函數(shù)名解耦

//當(dāng)你需要寫一個遞歸函數(shù)的時候,你聲明了一個函數(shù)名,但是每次修改函數(shù)名的時候總會忘記修改內(nèi)部的函數(shù)名。argument 為函數(shù)內(nèi)部對象,包含傳入函數(shù)的所有參數(shù),arguments.callee 代表函數(shù)名。

// 這是一個最基礎(chǔ)的斐波那契數(shù)列
function fibonacci (n) {
    const fn = arguments.callee
    if (n &lt;= 1) return 1
    return fn(n - 1) + fn(n - 2)
}

14、隱顯判斷

//當(dāng)你需要對一個 dom 元素進(jìn)行判斷當(dāng)前是否出現(xiàn)在頁面視圖內(nèi),你可以嘗試用 IntersectionObserver 進(jìn)行判斷
<style>
.item {
    height: 350px;
}
</style>
<div class="container">
  <div class="item" data-id="1">不可見</div>
  <div class="item" data-id="2">不可見</div>
  <div class="item" data-id="3">不可見</div>
</div>
<script>
  if (window?.IntersectionObserver) {
    let items = [...document.getElementsByClassName("item")]; // 解析為真數(shù)組,也可用 Array.prototype.slice.call()
    let io = new IntersectionObserver(
      (entries) => {
        entries.forEach((item) => {
          item.target.innerHTML =
            item.intersectionRatio === 1 // 元素顯示比例,為1時完全可見,為0時完全不可見
              ? `元素完全可見`
              : `元素部分不可見`;
        });
      },
      {
        root: null,
        rootMargin: "0px 0px",
        threshold: 1, // 閥值設(shè)為1,當(dāng)只有比例達(dá)到1時才觸發(fā)回調(diào)函數(shù)
      }
    );
    items.forEach((item) => io.observe(item));
  }
</script>

15、元素可編輯

//當(dāng)你需要在某個 dom 元素進(jìn)行編輯,讓它點擊的時候就像一個 textarea
<div contenteditable="true">這里是可編輯的內(nèi)容</div>

16、元素屬性監(jiān)聽

<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("屬性發(fā)生變化了", mutations);
  })
  observe.observe(el, {
    attributes: true
  });
  function handleClick() {
    el.setAttribute("style", "color: red");
    el.setAttribute("data-name", n++);
  }
  setTimeout(() => {
    observe.disconnect(); // 停止監(jiān)聽
  }, 5000);
</script>

17、打印 dom 元素

//當(dāng)你需要在開發(fā)過程中打印 dom 元素時,使用 console.log 往往只會打印出整個 dom 元素,而無法查看該 dom 元素的內(nèi)部屬性。你可以嘗試使用 console.dir

console.dir(document.body)

18、激活應(yīng)用

//當(dāng)你在移動端開發(fā)時,需要打開其他應(yīng)用。以下方法也可以通過 location.href 賦值操作
  <a href="tel:12345678910" rel="external nofollow" >電話</a>
  <a href="sms:12345678910,12345678911?body=你好" rel="external nofollow" >android短信</a>
  <a href="sms:/open?addresses=12345678910,12345678911&body=你好" rel="external nofollow" >ios短信</a>
  <a href="wx://" rel="external nofollow" >ios短信</a>

以上就是js常用方法示例梳理總結(jié)的詳細(xì)內(nèi)容,更多關(guān)于js常用方法示例的資料請關(guān)注腳本之家其它相關(guān)文章!

相關(guān)文章

最新評論