web 前端零散知识

css 禁止选中

1 * {
2     -moz-user-select: none;
3     -webkit-user-select: none;
4     -ms-user-select: none;
5     -khtml-user-select: none;
6     -o-user-select: none;
7     user-select: none;
8 }

js 禁止选中

1 document.addEventListener("selectstart", function (e) {
2     e.preventDefault();
3 });

js 禁止通过快捷键打开开发者工具

1 document.addEventListener("keydown", function (e) {
2     if (e.key === "F12" || (e.ctrlKey && e.shiftKey && e.key === "I")) {
3         e.preventDefault();
4     }
5 });

js 禁用右键菜单

1 document.addEventListener("contextmenu", function (e) {
2     e.preventDefault();
3 });

js 查找匿名事件监听器

  1. getEventListeners(domElement) 可以得到该元素的全部事件监听器列表
  2. 重新定义 addEventListener

js 选区

 1 function select(dom) {
 2   if (!dom) return;
 3   const selection = window.getSelection();
 4   if (
 5     dom instanceof HTMLInputElement ||
 6     dom instanceof HTMLTextAreaElement
 7   ) {
 8     dom.select();
 9   } else {
10     const range = document.createRange();
11     range.selectNode(dom);
12 
13     // range.setStart(dom, 1);
14     // range.setEnd(dom, 2);
15 
16     if (selection.rangeCount > 0) {
17       selection.removeAllRanges();
18     }
19     selection.addRange(range);
20   }
21   return selection;
22 }

js 复制

 1 function copy(dom) {
 2   if (!dom) return;
 3   const selection = select(dom);
 4   if (navigator.clipboard) {
 5     navigator.clipboard.writeText(
 6       selection.toString().replace(/\s+/, "")
 7     );
 8   } else {
 9     document.execCommand("copy");
10   }
11 }

js 判断 PC 端还是移动端

  1. navigator.userAgent
  2. navigator.platform

css 设置选中文本的样式

 1 ::selection {
 2     background-color: #ff645d;
 3     color: white;
 4 }
 5 ::-moz-selection {
 6     background-color: #ff645d;
 7     color: white;
 8 }
 9 ::-webkit-selection {
10     background-color: #ff645d;
11     color: white;
12 }

js 通过字符串创建 html

1 function stringToHTML(str) {
2     var parser = new DOMParser();
3     var doc = parser.parseFromString(str, "text/html");
4     return doc.body;
5 }

css 定义滚动条

1 ::-webkit-scrollbar {
2     width: 8px;
3     height: 8px;
4 }
5 ::-webkit-scrollbar-thumb {
6     border-radius: 4px;
7     background: #aaa;
8 }

 

posted @ 2022-11-23 18:54  万物有序  阅读(21)  评论(0编辑  收藏  举报