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