# 窗口相关
浏览器、窗口、地址栏、复制等相关的 JS 代码。
# 复制到剪贴板
function CopyToClipboard(containerid) { if (window.getSelection) { if
(window.getSelection().empty) { // Chrome window.getSelection().empty(); } else if
(window.getSelection().removeAllRanges) { // Firefox window.getSelection().removeAllRanges(); } }
else if (document.selection) { // IE? document.selection.empty(); } if (document.selection) { var
range = document.body.createTextRange();
range.moveToElementText(document.getElementById(containerid)); range.select().createTextRange();
document.execCommand("copy"); } else if (window.getSelection) { var range = document.createRange();
range.selectNode(document.getElementById(containerid)); window.getSelection().addRange(range);
document.execCommand("copy"); } }
navigator 方法
const copyToClipboard = (text) => navigator.clipboard.writeText(text);
copyToClipboard("Hello World");
# 获取用户选择的文本
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
从 HTML 中获取内容
const getTextInHTML = html => (new DOMParser().parseFromString(html, 'text/html')).body.textContent || '';
getTextInHTML('Hello World'); /*'Hello World'*/
# 浏览器型号和版本
export const getExplorerInfo = () => {
let t = navigator.userAgent.toLowerCase();
return 0 <= t.indexOf("msie") ? { //ie < 11
type: "IE",
version: Number(t.match(/msie ([\d]+)/)[1])
} : !!t.match(/trident\/.+?rv:(([\d.]+))/) ? { // ie 11
type: "IE",
version: 11
} : 0 <= t.indexOf("edge") ? {
type: "Edge",
version: Number(t.match(/edge\/([\d]+)/)[1])
} : 0 <= t.indexOf("firefox") ? {
type: "Firefox",
version: Number(t.match(/firefox\/([\d]+)/)[1])
} : 0 <= t.indexOf("chrome") ? {
type: "Chrome",
version: Number(t.match(/chrome\/([\d]+)/)[1])
} : 0 <= t.indexOf("opera") ? {
type: "Opera",
version: Number(t.match(/opera.([\d]+)/)[1])
} : 0 <= t.indexOf("Safari") ? {
type: "Safari",
version: Number(t.match(/version\/([\d]+)/)[1])
} : {
type: t,
version: -1
}
}
判断是否是微信/QQ 内置浏览器
export const broswer = () => {
const ua = navigator.userAgent.toLowerCase();
if (ua.match(/MicroMessenger/i) == "micromessenger") {
return "weixin";
} else if (ua.match(/QQ/i) == "qq") {
return "QQ";
}
return false;
}
当前运行时环境是否为浏览器
const isBrowser = () => ![typeof window, typeof document].includes('undefined');
isBrowser(); // true (browser)
isBrowser(); // false (Node)
# 在特定元素的末尾插入 HTML 字符串
const insertAfter = (el, htmlString) => el.insertAdjacentHTML('afterend', htmlString);
insertAfter(document.getElementById('myId'), 'after
'); // ... after
之前
const insertBefore = (el, htmlString) => el.insertAdjacentHTML('beforebegin', htmlString);
insertBefore(document.getElementById('myId'), 'before
'); // before
...
# 获取窗口区域
滚动到页面顶部
const scrollToTop = () => window.scrollTo(0, 0);
scrollToTop();
或者:
export const scrollToTop = () => {
const height = document.documentElement.scrollTop || document.body.scrollTop;
if (height > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, height - height / 8);
}
}
滚动到页面底部
export const scrollToBottom = () => {
window.scrollTo(0, document.documentElement.clientHeight);
}
滚动到指定元素区域
export const smoothScroll = (element) => {
document.querySelector(element).scrollIntoView({
behavior: 'smooth'
});
};
smoothScroll('#target'); // 平滑滚动到 ID 为 target 的元素
检查页面底部是否可见
const bottomVisible = () =>
document.documentElement.clientHeight + window.scrollY >=
(document.documentElement.scrollHeight || document.documentElement.clientHeight);
bottomVisible(); // true
获取可视窗口高度
export const replaceParamVal => (paramName, replaceWith) {
const oUrl = location.href.toString();
const re = eval('/('+ paramName+'=)([^&]*)/gi');
location.href = oUrl.replace(re,paramName+'='+replaceWith);
return location.href;
}
获取可视窗口宽度
export const getPageViewWidth = () => {
return (document.compatMode == "BackCompat" ? document.body : document.documentElement).clientWidth;
}
# 处理 URL 相关
返回当前 URL
const currentURL = () => window.location.href;
URL 获取查询参数 1
const getParameters = (URL) => {
URL = JSON.parse(
'{"' +
decodeURI(URL.split("?")[1])
.replace(/"/g, '\\"')
.replace(/&/g, '","')
.replace(/=/g, '":"') +
'"}'
);
return JSON.stringify(URL);
};
getParameters(window.location);
// Result: { search : "easy", page : 3 }
URL 获取查询参数 2
export const getSearchParams = () => {
const searchPar = new URLSearchParams(window.location.search)
const paramsObj = {}
for (const [key, value] of searchPar.entries()) {
paramsObj[key] = value
}
return paramsObj
}
// 假设目前位于 https://****com/index?id=124513&age=12;
getSearchParams(); // {id: "124513", age: "12"}
修改 URL 中的参数
export const replaceParamVal => (paramName, replaceWith) {
const oUrl = location.href.toString();
const re = eval('/('+ paramName+'=)([^&]*)/gi');
location.href = oUrl.replace(re,paramName+'='+replaceWith);
return location.href;
}
删除 URL 中指定参数
export const funcUrlDel = (name) => {
const baseUrl = location.origin + location.pathname + "?";
const query = location.search.substr(1);
if (query.indexOf(name) > -1) {
const obj = {};
const arr = query.split("&");
for (let i = 0; i < arr.length; i++) {
arr[i] = arr[i].split("=");
obj[arr[i][0]] = arr[i][1];
}
delete obj[name];
return baseUrl + JSON.stringify(obj).replace(/[\"\{\}]/g,"").replace(/\:/g,"=").replace(/\,/g,"&");
}
}
# 颜色 RGB 转十六进制
const rgbToHex = (r, g, b) => "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);
rgbToHex(0, 51, 255);
// Result: #0033ff
生成随机十六进制颜色
const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`;
console.log(randomHex());
// Result: #92b008
# 浏览器选项卡是否获得焦点
const isBrowserTabFocused = () => !document.hidden;
isBrowserTabFocused(); // true
# 设置浏览器 Cookie 的值
export const setCookie = (key, value, expire) => {
const d = new Date();
d.setDate(d.getDate() + expire);
document.cookie = `${key}=${value};expires=${d.toUTCString()}`
};
清除全部 Cookie
const clearCookies = document.cookie.split(';').forEach(cookie => document.cookie = cookie.replace(/^ +/, '').replace(/=.*/, `=;expires=${new Date(0).toUTCString()};path=/`));
指定cookie:
export const delCookie = (key) => {
document.cookie = `${encodeURIComponent(key)}=;expires=${new Date()}`
};
# 浏览器全屏
export const toFullScreen = () => {
let 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()
}
}
退出全屏
export 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()
}
}
# 打开浏览器打印框
const showPrintDialog = () => window.print()
# 存储封装操作
class MyCache {
constructor(isLocal = true) {
this.storage = isLocal ? localStorage : sessionStorage
}
setItem(key, value) {
if (typeof (value) === 'object') value = JSON.stringify(value)
this.storage.setItem(key, value)
}
getItem(key) {
try {
return JSON.parse(this.storage.getItem(key))
} catch (err) {
return this.storage.getItem(key)
}
}
removeItem(key) {
this.storage.removeItem(key)
}
clear() {
this.storage.clear()
}
key(index) {
return this.storage.key(index)
}
length() {
return this.storage.length
}
}
const localCache = new MyCache()
const sessionCache = new MyCache(false)
export { localCache, sessionCache }
示例
localCache.getItem('user')
sessionCache.setItem('name','树哥')
sessionCache.getItem('token')
localCache.clear()
# 重定向到一个 URL
const redirect = url => location.href = url
redirect("https://www.google.com/")
# 确定当前选项卡是否处于活动状态
const isTabInView = () => !document.hidden;
# 检索选择的文本
//该方法通过内置的 getSelection 属性获取用户选择的文本
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
# 停止冒泡事件
const stopPropagation = (event) => {
event = event || window.event;
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
};
# 获取浏览器类型及其版本
const getExplorerInfo = () => {
let t = navigator.userAgent.toLowerCase();
return 0 <= t.indexOf("msie")
? {
//ie < 11
type: "IE",
version: Number(t.match(/msie ([\d]+)/)[1]),
}
: !!t.match(/trident\/.+?rv:(([\d.]+))/)
? {
// ie 11
type: "IE",
version: 11,
}
: 0 <= t.indexOf("edge")
? {
type: "Edge",
version: Number(t.match(/edge\/([\d]+)/)[1]),
}
: 0 <= t.indexOf("firefox")
? {
type: "Firefox",
version: Number(t.match(/firefox\/([\d]+)/)[1]),
}
: 0 <= t.indexOf("chrome")
? {
type: "Chrome",
version: Number(t.match(/chrome\/([\d]+)/)[1]),
}
: 0 <= t.indexOf("opera")
? {
type: "Opera",
version: Number(t.match(/opera.([\d]+)/)[1]),
}
: 0 <= t.indexOf("Safari")
? {
type: "Safari",
version: Number(t.match(/version\/([\d]+)/)[1]),
}
: {
type: t,
version: -1,
};
};
# 检测是否 url 地址
export const isURL = (s) => {
return /^http[s]?:\/\/.*/.test(s)
}
# 根据 url 地址下载
export const download = (url) => {
var isChrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
var isSafari = navigator.userAgent.toLowerCase().indexOf('safari') > -1;
if (isChrome || isSafari) {
var link = document.createElement('a');
link.href = url;
if (link.download !== undefined) {
var fileName = url.substring(url.lastIndexOf('/') + 1, url.length);
link.download = fileName;
}
if (document.createEvent) {
var e = document.createEvent('MouseEvents');
e.initEvent('click', true, true);
link.dispatchEvent(e);
return true;
}
}
if (url.indexOf('?') === -1) {
url += '?download';
}
window.open(url, '_self');
return true;
}
# 劫持粘贴板
export const copyTextToClipboard = (value) => {
var textArea = document.createElement("textarea");
textArea.style.background = 'transparent';
textArea.value = value;
document.body.appendChild(textArea);
textArea.select();
try {
var successful = document.execCommand('copy');
} catch (err) {
console.log('前端南玖');
}
document.body.removeChild(textArea);
}
获取用户选择的文本
const getSelectedText = () => window.getSelection().toString();
getSelectedText();
# 16 进制颜色转 RGB/RGBA 字符串
export const colorToRGB = (val, opa) => {
var pattern = /^(#?)[a-fA-F0-9]{6}$/; //16进制颜色值校验规则
var isOpa = typeof opa == 'number'; //判断是否有设置不透明度
if (!pattern.test(val)) { //如果值不符合规则返回空字符
return '';
}
var v = val.replace(/#/, ''); //如果有#号先去除#号
var rgbArr = [];
var rgbStr = '';
for (var i = 0; i < 3; i++) {
var item = v.substring(i * 2, i * 2 + 2);
var num = parseInt(item, 16);
rgbArr.push(num);
}
rgbStr = rgbArr.join();
rgbStr = 'rgb' + (isOpa ? 'a' : '') + '(' + rgbStr + (isOpa ? ',' + opa : '') + ')';
return rgbStr;
}
# 检查元素是否聚焦
const elementFocus = (el) => (el === document.activeElement);
elementIsInFocus(element);
# 度数转换为弧度
const degreesToRads = deg => (deg * Math.PI) / 180.0;
degreesToRads(90.0); // ~1.5708
# 返回两点之间的距离
const distance = (x0, y0, x1, y1) => Math.hypot(x1 - x0, y1 - y0);
distance(1, 1, 2, 3); // 2.23606797749979