浏览器相关

禁止选择和复制

  1. ['contextmenu', 'selectstart', 'copy'].forEach(function(ev){
  2. document.addEventListener(ev, function(ev){
  3. ev.preventDefault();
  4. ev.returnValue = false;
  5. })
  6. });
  1. body {
  2. -moz-user-select: none;
  3. -webkit-user-select: none;
  4. -ms-user-select: none;
  5. -khtml-user-select: none;
  6. user-select: none;
  7. }

浏览器全屏

toFullScreen:全屏

  1. function toFullScreen() {
  2. const elem: any = document.body
  3. elem.webkitRequestFullScreen
  4. ? elem.webkitRequestFullScreen()
  5. : elem.mozRequestFullScreen
  6. ? elem.mozRequestFullScreen()
  7. : elem.msRequestFullscreen
  8. ? elem.msRequestFullscreen()
  9. : elem.requestFullScreen
  10. ? elem.requestFullScreen()
  11. : alert('浏览器不支持全屏')
  12. }

exitFullscreen:退出全屏

  1. function exitFullscreen() {
  2. const elem: any = parent.document
  3. elem.webkitCancelFullScreen
  4. ? elem.webkitCancelFullScreen()
  5. : elem.mozCancelFullScreen
  6. ? elem.mozCancelFullScreen()
  7. : elem.cancelFullScreen
  8. ? elem.cancelFullScreen()
  9. : elem.msExitFullscreen
  10. ? elem.msExitFullscreen()
  11. : elem.exitFullscreen
  12. ? elem.exitFullscreen()
  13. : alert('切换失败,可尝试Esc退出')
  14. }

isFullscreen

  1. function isFullscreen() {
  2. return (
  3. document.fullscreenElement ||
  4. document.msFullscreenElement ||
  5. document.mozFullScreenElement ||
  6. document.webkitFullscreenElement ||
  7. false
  8. )
  9. }
  1. function toggleFullscreen() {
  2. if (isFullscreen()) {
  3. exitFullscreen()
  4. } else {
  5. toFullScreen()
  6. }
  7. }

复制到剪贴板

https://www.zhangxinxu.com/wordpress/2021/10/js-copy-paste-clipboard/
https://gitee.com/zhangxinxu/copy-text

  1. const copyToClipboard = (text) =>
  2. navigator.clipboard?.writeText && navigator.clipboard.writeTexttext)。
  3. // 测试
  4. copyToClipboard("Hello World!")。
  1. // 只能赋值在setup中使用
  2. import { message } from 'ant-design-vue'
  3. import { useI18n } from '@/hooks'
  4. export default function useCopyText() {
  5. const { $t } = useI18n()
  6. return (text: string) => {
  7. try {
  8. const data = text
  9. const newInput = document.createElement('textarea')
  10. newInput.value = data
  11. document.body.appendChild(newInput)
  12. newInput.select()
  13. document.execCommand('Copy')
  14. newInput.remove()
  15. message.success($t('message.copySuccess'))
  16. } catch (e) {
  17. console.log(e)
  18. message.success($t('message.copyFailed'))
  19. }
  20. }
  21. }
  1. // https://www.30secondsofcode.org/js/s/copy-to-clipboard/
  2. const copyToClipboard = str => {
  3. const el = document.createElement('textarea');
  4. el.value = str;
  5. el.setAttribute('readonly', '');
  6. el.style.position = 'absolute';
  7. el.style.left = '-9999px';
  8. document.body.appendChild(el);
  9. const selected =
  10. document.getSelection().rangeCount > 0
  11. ? document.getSelection().getRangeAt(0)
  12. : false;
  13. el.select();
  14. document.execCommand('copy');
  15. document.body.removeChild(el);
  16. if (selected) {
  17. document.getSelection().removeAllRanges();
  18. document.getSelection().addRange(selected);
  19. }
  20. };
  21. copyToClipboard('Lorem ipsum'); // 'Lorem ipsum' copied to clipboard.

检测黑暗模式

  1. const isDarkMode = () =>
  2. window.matchMedia &&
  3. window.matchMedia("(prefers-color-scheme: dark)").matches
  4. // 测试
  5. console.log(isDarkMode())。

元素滚动到顶部 / 底部

  1. const scrollToTop = (element) =>
  2. element.scrollIntoView({ behavior: "smooth", block: "start" })
  3. const scrollToBottom = (element) =>
  4. element.scrollIntoView({ behavior: "smooth", block: "end" })
  1. backTop() {
  2. if (this.el.scrollTop === 0 || this.isBackTop) {
  3. return
  4. }
  5. this.isBackTop = true
  6. const el = this.el
  7. const beginTime = Date.now()
  8. const beginValue = el.scrollTop
  9. const rAF =
  10. window.requestAnimationFrame || ((func) => setTimeout(func, 16))
  11. const frameFunc = () => {
  12. const progress = (Date.now() - beginTime) / 500
  13. if (progress < 1) {
  14. el.scrollTop = beginValue * (1 - easeInOutCubic(progress))
  15. rAF(frameFunc)
  16. } else {
  17. el.scrollTop = 0
  18. this.isBackTop = false
  19. }
  20. }
  21. rAF(frameFunc)
  22. }

生成随机颜色

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

文件下载

base64数据导出文件,文件下载

  1. function downloadFile(filename, data) {
  2. let DownloadLink = document.createElement('a');
  3. if (DownloadLink) {
  4. document.body.appendChild(DownloadLink);
  5. DownloadLink.style = 'display: none';
  6. DownloadLink.download = filename;
  7. DownloadLink.href = data;
  8. if (document.createEvent) {
  9. let DownloadEvt = document.createEvent('MouseEvents');
  10. DownloadEvt.initEvent('click', true, false);
  11. DownloadLink.dispatchEvent(DownloadEvt);
  12. } else if (document.createEventObject) {
  13. DownloadLink.fireEvent('onclick');
  14. } else if (typeof DownloadLink.onclick == 'function') {
  15. DownloadLink.onclick();
  16. }
  17. document.body.removeChild(DownloadLink);
  18. }
  19. }

网站、网页实现屏幕录像功能

  1. var body = document.body;
  2. body.addEventListener("click",async function(){
  3. var stream = await navigator.mediaDevices.getDisplayMedia({video: true});
  4. var mime = MediaRecorder.isTypeSupported("video/webm; codecs=vp9") ? "video/webm; codecs=vp9" :"video/webm";
  5. var mediaRecorder = new MediaRecorder(stream, {mimeType: mime});
  6. //录制
  7. var chunks = [];
  8. mediaRecorder.addEventListener('dataavailable', function(e) {
  9. chunks.push(e.data)
  10. })
  11. //停止
  12. mediaRecorder.addEventListener('stop', function(){
  13. var blob = new Blob(chunks, {type: chunks[0].type});
  14. var url = URL.createObjectURL(blob);
  15. var a = document.createElement('a');
  16. a.href = url;
  17. a.download = 'video.webm';
  18. a.click();
  19. })
  20. //手动启动
  21. mediaRecorder.start()
  22. });


判断浏览器环境

  1. function getSystem(){
  2. const mac = /mac/i,
  3. linux = /linux/i,
  4. win = /win/i;
  5. const platform = navigator.platform.toLowerCase();
  6. if(mac.test(platform)){
  7. return 'MAC';
  8. } else if(win.test(platform)){
  9. return 'WIN';
  10. } else if(linux.test(platform)){
  11. return 'Linux';
  12. }
  13. return undefined;
  14. }
  15. const browser = {
  16. versions:function(){
  17. let ret = 'xxSys';
  18. const u = navigator.userAgent;
  19. const isMobile = !!u.match(/AppleWebKit.*Mobile.*/),
  20. ios = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/),
  21. android = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1;
  22. if(isMobile){
  23. if(ios) return 'IOS';
  24. if(android) return 'Android';
  25. } else {
  26. ret = getSystem() || ret;
  27. }
  28. return ret;
  29. }(),
  30. };
  31. export default browser;

使用

  1. import browser from "../util/browers.js"
  2. console.log(browser.versions);

加入收藏夹

  1. function addFavorite(sURL, sTitle) {
  2. try {
  3. window.external.addFavorite(sURL, sTitle);
  4. } catch (e) {
  5. try {
  6. window.sidebar.addPanel(sTitle, sURL, "");
  7. } catch (e) {
  8. alert("加入收藏失败,请使用Ctrl+D进行添加");
  9. }
  10. }
  11. }