js 常用功能语句
复制内容到剪贴板
js
复制代码
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
清除所有cookie
js
复制代码
const clearCookies = document.cookie.split(';').forEach(cookie => {
document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`)
});
获取选中的文字
js
复制代码
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
滚动到页面顶部
js
复制代码
const goToTop = () => window.scrollTo(0, 0);
goToTop();
是否滚动到页面底部
js
复制代码
const scrolledToBottom = () => document.documentElement.clientHeight + window.scrollY >= document.documentElement.scrollHeight;
判断当前tab是否激活
js
复制代码
const isTabInView = () => !document.hidden;
判断当前设备是否为苹果设备
js
复制代码
const isAppleDevice = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);
isAppleDevice();
判断是否是微信内置浏览器打开
js
复制代码
export function isWeChat() {
return /MicroMessenger/i.test(window.navigator.userAgent) && /Mobile/i.test(window.navigator.userAgent)
}
获取变量的类型
js
复制代码
const trueTypeOf = (obj) => Object.prototype.toString.call(obj).slice(8, -1).toLowerCase();
trueTypeOf('');
检查对象是否为空
js
复制代码
const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
随机字符串
js
复制代码
const randomString = () => Math.random().toString(36).slice(2);
randomString();
从字符串中删除 HTML
js
复制代码
const stripHtml = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
检查数组是否为空
js
复制代码
const isNotEmpty = arr => Array.isArray(arr) && arr.length > 0;
isNotEmpty([1, 2, 3]);