禁止选择和复制
['contextmenu', 'selectstart', 'copy'].forEach(function(ev){
document.addEventListener(ev, function(ev){
ev.preventDefault();
ev.returnValue = false;
})
});
body {
-moz-user-select: none;
-webkit-user-select: none;
-ms-user-select: none;
-khtml-user-select: none;
user-select: none;
}
浏览器全屏
toFullScreen:全屏
function toFullScreen() {
const elem: any = document.body
elem.webkitRequestFullScreen
? elem.webkitRequestFullScreen()
: elem.mozRequestFullScreen
? elem.mozRequestFullScreen()
: elem.msRequestFullscreen
? elem.msRequestFullscreen()
: elem.requestFullScreen
? elem.requestFullScreen()
: alert('浏览器不支持全屏')
}
exitFullscreen:退出全屏
function exitFullscreen() {
const elem: any = parent.document
elem.webkitCancelFullScreen
? elem.webkitCancelFullScreen()
: elem.mozCancelFullScreen
? elem.mozCancelFullScreen()
: elem.cancelFullScreen
? elem.cancelFullScreen()
: elem.msExitFullscreen
? elem.msExitFullscreen()
: elem.exitFullscreen
? elem.exitFullscreen()
: alert('切换失败,可尝试Esc退出')
}
isFullscreen
function isFullscreen() {
return (
document.fullscreenElement ||
document.msFullscreenElement ||
document.mozFullScreenElement ||
document.webkitFullscreenElement ||
false
)
}
function toggleFullscreen() {
if (isFullscreen()) {
exitFullscreen()
} else {
toFullScreen()
}
}
复制到剪贴板
https://www.zhangxinxu.com/wordpress/2021/10/js-copy-paste-clipboard/
https://gitee.com/zhangxinxu/copy-text
const copyToClipboard = (text) =>
navigator.clipboard?.writeText && navigator.clipboard.writeText(text)。
// 测试
copyToClipboard("Hello World!")。
// 只能赋值在setup中使用
import { message } from 'ant-design-vue'
import { useI18n } from '@/hooks'
export default function useCopyText() {
const { $t } = useI18n()
return (text: string) => {
try {
const data = text
const newInput = document.createElement('textarea')
newInput.value = data
document.body.appendChild(newInput)
newInput.select()
document.execCommand('Copy')
newInput.remove()
message.success($t('message.copySuccess'))
} catch (e) {
console.log(e)
message.success($t('message.copyFailed'))
}
}
}
// https://www.30secondsofcode.org/js/s/copy-to-clipboard/
const copyToClipboard = str => {
const el = document.createElement('textarea');
el.value = str;
el.setAttribute('readonly', '');
el.style.position = 'absolute';
el.style.left = '-9999px';
document.body.appendChild(el);
const selected =
document.getSelection().rangeCount > 0
? document.getSelection().getRangeAt(0)
: false;
el.select();
document.execCommand('copy');
document.body.removeChild(el);
if (selected) {
document.getSelection().removeAllRanges();
document.getSelection().addRange(selected);
}
};
copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.
检测黑暗模式
const isDarkMode = () =>
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches
// 测试
console.log(isDarkMode())。
元素滚动到顶部 / 底部
const scrollToTop = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "start" })
const scrollToBottom = (element) =>
element.scrollIntoView({ behavior: "smooth", block: "end" })
backTop() {
if (this.el.scrollTop === 0 || this.isBackTop) {
return
}
this.isBackTop = true
const el = this.el
const beginTime = Date.now()
const beginValue = el.scrollTop
const rAF =
window.requestAnimationFrame || ((func) => setTimeout(func, 16))
const frameFunc = () => {
const progress = (Date.now() - beginTime) / 500
if (progress < 1) {
el.scrollTop = beginValue * (1 - easeInOutCubic(progress))
rAF(frameFunc)
} else {
el.scrollTop = 0
this.isBackTop = false
}
}
rAF(frameFunc)
}
生成随机颜色
const generateRandomHexColor = () =>
\`#${Math.floor(Math.random() \* 0xffffff) .toString(16)}\`;
文件下载
base64数据导出文件,文件下载
function downloadFile(filename, data) {
let DownloadLink = document.createElement('a');
if (DownloadLink) {
document.body.appendChild(DownloadLink);
DownloadLink.style = 'display: none';
DownloadLink.download = filename;
DownloadLink.href = data;
if (document.createEvent) {
let DownloadEvt = document.createEvent('MouseEvents');
DownloadEvt.initEvent('click', true, false);
DownloadLink.dispatchEvent(DownloadEvt);
} else if (document.createEventObject) {
DownloadLink.fireEvent('onclick');
} else if (typeof DownloadLink.onclick == 'function') {
DownloadLink.onclick();
}
document.body.removeChild(DownloadLink);
}
}
网站、网页实现屏幕录像功能
var body = document.body;
body.addEventListener("click",async function(){
var stream = await navigator.mediaDevices.getDisplayMedia({video: true});
var mime = MediaRecorder.isTypeSupported("video/webm; codecs=vp9") ? "video/webm; codecs=vp9" :"video/webm";
var mediaRecorder = new MediaRecorder(stream, {mimeType: mime});
//录制
var chunks = [];
mediaRecorder.addEventListener('dataavailable', function(e) {
chunks.push(e.data)
})
//停止
mediaRecorder.addEventListener('stop', function(){
var blob = new Blob(chunks, {type: chunks[0].type});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.href = url;
a.download = 'video.webm';
a.click();
})
//手动启动
mediaRecorder.start()
});
判断浏览器环境
function getSystem(){
const mac = /mac/i,
linux = /linux/i,
win = /win/i;
const platform = navigator.platform.toLowerCase();
if(mac.test(platform)){
return 'MAC';
} else if(win.test(platform)){
return 'WIN';
} else if(linux.test(platform)){
return 'Linux';
}
return undefined;
}
const browser = {
versions:function(){
let ret = 'xxSys';
const u = navigator.userAgent;
const isMobile = !!u.match(/AppleWebKit.*Mobile.*/),
ios = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
android = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
if(isMobile){
if(ios) return 'IOS';
if(android) return 'Android';
} else {
ret = getSystem() || ret;
}
return ret;
}(),
};
export default browser;
使用
import browser from "../util/browers.js"
console.log(browser.versions);
加入收藏夹
function addFavorite(sURL, sTitle) {
try {
window.external.addFavorite(sURL, sTitle);
} catch (e) {
try {
window.sidebar.addPanel(sTitle, sURL, "");
} catch (e) {
alert("加入收藏失败,请使用Ctrl+D进行添加");
}
}
}