1、實作全屏
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、列印内容樣式更改
<style>
/* 使用@media print可以調整你需要的列印樣式 */
@media print {
.noprint {
display: none;
}
}
</style>
<div class="print">print</div>
<div class="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 = new MediaRecorder(stream, options);// 初始化MediaRecorder執行個體
mediaRecorder.ondataavailable = handleDataAvailable;// 設定資料可用(錄屏結束)時的回調
mediaRecorder.start();
// 視訊碎片合并
function handleDataAvailable(event) {
if (event.data.size > 0) {
recordedChunks.push(event.data);// 添加資料,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("豎屏狀态!")
}
if(window.orientation==90||window.orientation==-90){
alert("橫屏狀态!")
}
}
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、标簽頁顯隐
//當你需要對标簽頁顯示隐藏進行事件監聽時
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("目前被隐藏", 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'])
12、字元串腳本化
//當你需要将一串字元串轉換成一個 js 腳本,該方法有 xss 漏洞,慎用
const obj = eval('({ name: "jack" })')
// obj會被轉換為對象{ name: "jack" }
const v = eval('obj')
// v會變成obj這個變量
13、遞歸函數名解耦
//當你需要寫一個遞歸函數的時候,你聲明了一個函數名,但是每次修改函數名的時候總會忘記修改内部的函數名。argument 為函數内部對象,包含傳入函數的所有參數,arguments.callee 代表函數名。
// 這是一個最基礎的斐波那契數列
function fibonacci (n) {
const fn = arguments.callee
if (n <= 1) return 1
return fn(n - 1) + fn(n - 2)
}
14、隐顯判斷
//當你需要對一個 dom 元素進行判斷目前是否出現在頁面視圖内,你可以嘗試用 IntersectionObserver 進行判斷
<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")]; // 解析為真數組,也可用 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, // 閥值設為1,當隻有比例達到1時才觸發回調函數
}
);
items.forEach((item) => io.observe(item));
}
</script>
15、元素可編輯
//當你需要在某個 dom 元素進行編輯,讓它點選的時候就像一個 textarea
<div contenteditable="true">這裡是可編輯的内容</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("屬性發生變化了", mutations);
})
observe.observe(el, {
attributes: true
});
function handleClick() {
el.setAttribute("style", "color: red");
el.setAttribute("data-name", n++);
}
setTimeout(() => {
observe.disconnect(); // 停止監聽
}, 5000);
</script>
17、列印 dom 元素
//當你需要在開發過程中列印 dom 元素時,使用 console.log 往往隻會列印出整個 dom 元素,而無法檢視該 dom 元素的内部屬性。你可以嘗試使用 console.dir
console.dir(document.body)
18、激活應用
//當你在移動端開發時,需要打開其他應用。以下方法也可以通過 location.href 指派操作
<a href="tel:12345678910">電話</a>
<a href="sms:12345678910,12345678911?body=你好">android短信</a>
<a href="sms:/open?addresses=12345678910,12345678911&body=你好">ios短信</a>
<a href="wx://">ios短信</a>