0%

封装一些实用的js脚本功能

01、实现全屏
1
2
3
4
5
6
7
8
9
10
11
12
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、退出全屏
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
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、页面打印
1
window.print()
04、打印内容样式改变

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

1
2
3
4
5
6
7
8
9
10
<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事件,部分浏览器无法自定义文本内容。

1
2
3
window.onbeforeunload = function(){
return 'Are you sure you want to leave the haorooms blog?';
};
06、屏幕录制

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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、判断横竖屏
1
2
3
4
5
6
7
8
9
function hengshuping(){
if(window.orientation==180||window.orientation==0){
alert("Portrait state!")
}
if(window.orientation==90||window.orientation==-90){
alert("Landscape state!")
}
}
window.addEventListener("onorientationchange" in window ? "orientationchange" : "resize", hengshuping, false);
08、改变横竖屏的样式
1
2
3
4
5
6
7
8
9
10
11
12
<style>
@media all and (orientation : landscape) {
body {
background-color: #ff0000;
}
}
@media all and (orientation : portrait) {
body {
background-color: #00ff00;
}
}
</style>
09、标签页隐藏

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
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、本地图片预览

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<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、图片预加载
1
2
3
4
5
6
7
8
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、递归函数名解耦

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

1
2
3
4
5
function fibonacci (n) {
const fn = arguments.callee
if (n <= 1) return 1
return fn(n - 1) + fn(n - 2)
}
13、隐性判断

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<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>
14、元素属性监控
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<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>
15、激活应用

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

1
2
3
4
<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>
16、将内容复制到剪贴板
1
2
3
4
5
6
7
8
9
const copyToClipboard = (content) => {
const textarea = document.createElement("textarea")

textarea.value = content
document.body.appendChild(textarea)
textarea.select()
document.execCommand("Copy")
textarea.remove()
}
17、使用URLSearchParams获取URL的搜索参数
1
2
3
4
5
6
7
8
const getQueryByName = (name) => {
const query = new URLSearchParams(location.search)
return decodeURIComponent(query.get(name))
}
// url: https://sunday.com/?name=fatfish&age=100
const name = getQueryByName('name') // fatfish
const age = getQueryByName('age') // 100
const gender = getQueryByName('gender') // null
18、平滑滚动至页面顶部
1
2
3
4
5
6
7
8
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop

if (c > 0) {
window.requestAnimationFrame(scrollToTop)
window.scrollTo(0, c - c / 8)
}
}
19、获取当前页面滚动距离
1
2
3
4
5
6
const getScrollPosition = (el = window) => ({
x: el.pageXOffset !== undefined ? el.pageXOffset : el.scrollLeft,
y: el.pageYOffset !== undefined ? el.pageYOffset : el.scrollTop,
})

getScrollPosition() // { x: 0, y: 215 }
20、判断当前设备是Andoird还是iOS
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
function getOSType() {
let u = navigator.userAgent,
app = navigator.appVersion
let isAndroid = u.indexOf("Android") > -1 || u.indexOf("Linux") > -1
let isIOS = !!u.match(/\(i[^]+( U)? CPU.+Mac OS X/)

if (isIOS) {
return 0
} else if (isAndroid) {
return 1
} else {
return 2
}
}

getOSType() // 0
21、格式化货币
1
2
3
4
5
6
7
const formatMoney = (money) => {
return money.toLocaleString()
}

formatMoney(123456789) // '123,456,789'
formatMoney(123456789.123) // '123,456,789.123'
formatMoney(123) // '123'
-------------本文结束感谢您的阅读-------------