JavaScript 小技巧

1、滚动到页面顶部

使用 window.scrollTo() 平滑滚动到页面顶部。

1
2
3
4
5
// 方案一
window.scrollTo({ top: 0, left: 0, behavior: "smooth" });

// 方案儿
const scrollToTop = (element) => element.scrollIntoView({ behavior: "smooth", block: "start" })。

2、滚动到页面底部

使用 window.scrollTo() 也可以平滑滚动到页面底部。

1
2
3
4
5
6
7
8
9
// 方案一
window.scrollTo({
top: document.documentElement.offsetHeight,
left: 0,
behavior: "smooth",
});

// 方案二
const scrollToBottom = (element) => element.scrollIntoView({ behavior: "smooth", block: "end" })

3、滚动元素到可见区域

使用 scrollIntoView 平滑滚动到可见区域

1
2
3
element.scrollIntoView({
behavior: "smooth",
});

4、全屏显示元素

当需要全屏播放视频,并在浏览器中全屏打开页面。

1
2
3
4
5
6
7
8
9
10
11
12
const fullScreen = (element) => {
element = element || document.body;
if (element.requestFullscreen) {
element.requestFullscreen();
} else if (element.mozRequestFullScreen) {
element.mozRequestFullScreen();
} else if (element.msRequestFullscreen) {
element.msRequestFullscreen();
} else if (element.webkitRequestFullscreen) {
element.webkitRequestFullScreen();
}
};

5、退出浏览器全屏状态

退出浏览器全屏状态的场景,配合上面一起使用

1
2
3
4
5
6
7
8
9
10
11
const exitFullscreen = () => {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
}
};

6、获取数据类型

一个函数便可获取变量的数据类型

1
2
3
4
const getTypeof = (e) => {
const type = Object.prototype.toString.call(e).match(/ (\w+)]/)
return type[1].toLocaleLowerCase()
}

7、阻止冒泡事件

该方法应该适用所有平台(目前使用多个平台都是 OK 的)

1
2
3
4
5
6
7
8
const stopPropagation = (event) => {
event = event || window.event;
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
};

8、深拷贝对象

1
2
3
4
5
6
7
8
9
10
11
12
13
14
const deepClone = (obj, hash = new WeakMap()) => {
if (hash.has(obj)) return hash.get(obj);
if (obj instanceof Date) return new Date(obj)
if (obj instanceof RegExp) return new RegExp(obj)
if (typeof obj !== 'object') return obj
const res = Array.isArray(obj) ? [...obj] : { ...obj }
Object.keys(res).forEach(
(key) => (res[key] = isObject(res[key]) ? deepClone(res[key]) : res[key])
)
return res
}
const isObject = (obj) => {
return typeof obj === 'object' && typeof obj !== null
}

9、设置 cookies

1
2
3
4
5
const setCookie = (key, value, expire) => {
const d = new Date();
d.setDate(d.getDate() + expire);
document.cookie = `${key}=${value};expires=${d.toUTCString()}`;
};
1
2
3
4
5
6
7
8
9
10
11
12
13
const getCookie = (key) => {
const cookieStr = unescape(document.cookie);
const arr = cookieStr.split("; ");
let cookieValue = "";
for (let i = 0; i < arr.length; i++) {
const temp = arr[i].split("=");
if (temp[0] === key) {
cookieValue = temp[1];
break;
}
}
return cookieValue;
};

11、删除 cookies

1
2
3
const delCookie = (key) => {
document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`;
};

12、生成随机字符串

1
2
3
4
5
6
7
8
9
const randomString = (len) => {
let chars = "ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz123456789";
let strLen = chars.length;
let randomStr = "";
for (let i = 0; i < len; i++) {
randomStr += chars.charAt(Math.floor(Math.random() * strLen));
}
return randomStr;
};

13、字符串首字母大写

1
2
3
const fistLetterUpper = (str) => {
return str.charAt(0).toUpperCase() + str.slice(1);
};

14、生成指定范围内的随机数

1
const randomNum = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;

15、打乱数组排序

1
const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5)

16、复制到剪贴板

1
const copyToClipboard = (text) => navigator.clipboard?.writeText && navigator.clipboard.writeText(text)

17、检测黑暗模式

1
2
3
const isDarkMode = () =>
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches

18、生成随机颜色

1
const generateRandomHexColor = () =>  \`#${Math.floor(Math.random() \* 0xffffff) .toString(16)}\`;

19、防抖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
export const debounce = (() => {
let timer = null
return (callback, wait = 800) => {
timer&&clearTimeout(timer)
timer = setTimeout(callback, wait)
}
})()


<!-- 使用 -->
debounce(() => {
console.log('加载数据')
}, 500)

20、节流

1
2
3
4
5
6
7
8
9
10
export const throttle = (() => {
let last = 0
return (callback, wait = 800) => {
let now = +new Date()
if (now - last > wait) {
callback()
last = now
}
}
})()

21、手机号脱敏

1
2
3
export const hideMobile = (mobile) => {
return mobile.replace(/^(\d{3})\d{4}(\d{4})$/, "$1****$2")
}

22、简单的解析Url

1
2
3
4
5
6
7
8
9
export const getSearchParams = () => {
const searchPar = new URLSearchParams(window.location.search)
const paramsObj = {}
for (const [key, value] of searchPar.entries()) {
paramsObj[key] = value
}
return paramsObj
}

23、判断是Android还是ios

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/** 
* 1: ios
* 2: android
* 3: 其它
*/
export const 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 1;
}
if (isAndroid) {
return 2;
}
return 3;
}

24、在简单数组中求和、最小值、最大值

1
2
3
4
5
6
7
8
/** 求和 */
array.reduce((a,b) => a+b);

/** 最小值 */
array.reduce((a,b) => a<b?a:b);

/** 最大值 */
array.reduce((a,b) => a>b?a:b);

25、多条件||的简写

1
2
3
4
5
<!-- 多条件|| -->
if( type == 1 || type == 2 || type == 3 || type == 4){}

<!-- 简化 -->
if([1,2,3,4].includes(type)){}

26、网页变黑白(Css)

1
filter:grayscale(100%)

27、检查对象是否为空

1
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;

28、生成随机十六进制

1
const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`

29、检查当前选项卡是否在后台

1
const isTabActive = () => !document.hidden; 

30、检查设备类型

1
2
const judgeDeviceType =
() => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'PC';

31、获取选定的文本

1
const getSelectedText = () => window.getSelection().toString();