zl程序教程

您现在的位置是:首页 >  其他

当前栏目

前端开发中这些小技巧,你知道几个?

2023-03-09 22:08:36 时间

浏览器地址栏运行JavaScript代码

  1. javascript:alert('hello!'); 
  • Firefox不支持;
  • 其他浏览器必须手动输入才可执行;

浏览器地址栏运行HTML代码

  1. data:text/html,<h1>Hello, world!</h1> 
  • 在非IE浏览器可以运行

浏览器变成文本编辑器

地址栏输入:

  1. data:text/html, <html contenteditable> 

控制台输入:

  1. document.body.contentEditable='true'

利用a标签自动解析URL

  1. var a = document.createElement('a'); 
  2. a.href = 'https://www.maomin.club'
  3. console.log(a.host); // www.maomin.club 

页面拥有ID的元素会创建全局变量

  1. <!DOCTYPE html> 
  2. <html> 
  3. <head> 
  4.  <title></title> 
  5. </head> 
  6. <body> 
  7. <div id="app">我是内容</div> 
  8. <script type="text/javascript"
  9.  console.log(app.textContent) // 我是内容 
  10. </script> 
  11. </body> 
  12. </html> 

引用CDN文件时,不用HTTP标识

  1. <script src="//cdn.bootcdn.net/ajax/libs/vue/3.0.11/vue.cjs.js"></script> 

利用script标签保存任意信息

  1. <script type="text" id="template"
  2.  <h1>This won't display</h1> 
  3. </script> 
  4. <script type="text/javascript"
  5.  const text = document.getElementById('template').textContent; 
  6.  console.log(text); // <h1>This won't display</h1> 
  7. </script> 

 在页面中隐藏鼠标

  1. *{ 
  2.     cursor: none!important; 

文字模糊效果

  1. p { 
  2.     color: transparent; 
  3.     text-shadow: #111 0 0 5px; 

 实时编辑CSS

  1. <!DOCTYPE html> 
  2. <html> 
  3. <head> 
  4.  <title></title> 
  5.  <style type="text/css"
  6.   style{ 
  7.    display: block; 
  8.   } 
  9.  </style> 
  10. </head> 
  11. <body> 
  12.     <style  contentEditable> 
  13.          body { color: blue } 
  14.     </style> 
  15. </body> 
  16. </html> 

实现长宽比固定区域

  1. <div style="width: 100%; position: relative; padding-bottom: 56.25%;"
  2.     <div style="position: absolute; left: 0; top: 0; right: 0; bottom: 0;background-color:yellow;"
  3.         this content will have a constant aspect ratio that varies based on the width. 
  4.     </div> 
  5. </div> 

禁止他人使用iframe标签引用网址

  1. if (window.location != window.parent.location) window.parent.location = window.location; 

生成随机字符串

  1. function generateRandomAlphaNum(len) { 
  2.     var rdmString = ""
  3.     for (; rdmString.length < len; rdmString += Math.random().toString(36).substr(2)); 
  4.     return rdmString.substr(0, len); 

浮点数转化为整数

  1. console.log(~~1.2); // 1