前端开发技巧

89 阅读3分钟

计算文本宽度

const canvas = document.createElement('canvas')
const ctx = canvas.getContext('2d')
ctx.font = '12px Arial' //设置字体大小和样式
const text = 'Hello, world' //要计算宽度的字符串
const metrics = ctx.measureText(text) //计算字符串的宽度
console.log(metrics.width) //输出字符串宽度

首字母大写

'hello'.replace(/^(\w{1})/,(r)=>r.toUpperCase())

css遮罩背景模糊

<style>
    .demo-blur{
        position:relative;
        font-size:50px;
        color:#f00
    }
    .demo-blur:after{
        content: "";
        position:absolute;
        z-index:2;
        left:2;
        top:0;
        right:0;
        bottom:0;
        backdrop-filter:saturate(50%) blur(5px);
        background:rgba(255,255,255,.7)
    }
</style>
<div class="demo-blur">大傻子</div>

手机号码*号处理

''18212345678'.replace(/(\d{3}).*(\d{4})/,'$1****$2)

判断文本是否溢出

const isTextOverFlowed = (e)={
    if(e){
        return e.offsetWidth>=e.scrollWidth
    }
    return false
}

JSON.parse的作用

// 1.解析JSON字符串
JSON.parse('{"name":"tom"}')
JSON.parse('[1,2,3]')

//2.转换成数字
JSON.parse('12') //12

//3.转换成布尔值
JSON.parse('false') //false

css 给最后3个元素设置样式

<style>
    .demo li:nth-last-child(-n+3){
        /*负号表示计算从后往前的位置*/
        color#f00
    }
</style>
<ul>
    <li>a</li>
    <li>b</li>
    <li>c</li>
    <li>d</li>
    <li>e</li>
    <li>f</li>
    <li>g</li>
</ul>

驼峰命名与横杠命名互转

//驼峰转横杠
'liuDeHua'.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase() // liu-de-hua

//横杠转驼峰
'liu-de-hua'.replace(/-([a-z])/g, (match, p1) => p1.toUpperCase()) // liuDeHua

禁止右键、禁止F12

// 禁止右键
document.oncontextmenu = new Function("event.returnValue=false")

// 禁止F12
document.onkeydown = new Function("event.returnValue=false")

// 禁止打开控制台
setInterval(function() {
  var startTime = performance.now()
  // 设置断点
  debugger; 
  var endTime = performance.now()
  // 设置一个阈值,例如100毫秒
  if (endTime - startTime > 100) {
    window.location.href = 'about:blank'
  }  
}, 100)

随机订单号

function randomNumber() {
    const now = new Date()
    let month = now.getMonth() + 1
    let day = now.getDate()
    let hour = now.getHours()
    let minutes = now.getMinutes()
    let seconds = now.getSeconds()
    month = month < 10 ? "0" + month : month;
    day = day < 10 ? "0" + day : day;
    hour = hour < 10 ? "0" + hour : hour;
    minutes = minutes < 10 ? "0" + minutes : minutes;
    seconds = seconds < 10 ? "0" + seconds : seconds;
    let orderCode = now.getFullYear().toString() + month.toString() + day + hour + minutes + seconds + (Math.round(Math.random() * 1000000)).toString();
    return orderCode;
}

randomNumber() // 20221126173910839253

css变量使用

<style>
    /* 全局定义 */
    :root {
        --text-color: red;
    }
    strong {
        --text-color: blue; /* 局部重置 */
        color: var(--text-color);
    }
</style>
<strong>蓝色的Hello World</strong> 

去除数组if假数据

const arr = [1, 7, 3, 0, '', null, undefined, false]
const filterArr = arr.filter(Boolean)
console.log(filterArr) // [1, 7, 3]

人性化B、KB、GB、TB

function humanizeSize(fileSize){
  let size = "";
  if(fileSize < 0.1 * 1024){                              // 小于0.1KB,则转化成B
    size = fileSize.toFixed(2) + "B"
  } else if(fileSize < 0.1 * 1024 * 1024) {               // 小于0.1MB,则转化成KB
    size = (fileSize/1024).toFixed(2) + "KB"
  } else if(fileSize < 0.1 * 1024 * 1024 * 1024) {        // 小于0.1GB,则转化成MB
    size = (fileSize/(1024 * 1024)).toFixed(2) + "MB"
  } else {                                                // 其他转化成GB
    size = (fileSize/(1024 * 1024 * 1024)).toFixed(2) + "GB"
  }
  let sizeStr = size + "";                                // 转成字符串
  let index = sizeStr.indexOf(".");                       // 获取小数点处的索引
  let dou = sizeStr.substr(index + 1 ,2)                  // 获取小数点后两位的值
  if(dou == "00") {                                       // 判断后两位是否为00,如果是则删除00
    return sizeStr.substring(0, index) + sizeStr.substr(index + 3, 2)
  }
  return size;
}

var hsize = humanizeSize(77440);
console.log(hsize); // 75.63KB

画一条0.5px的直线

.zh-line {
  height: 1px;
  transform: scale(0.5);
}

文本两端对齐

<style>
    .zh-align-demo {
        width: 150px;
    }
    .zh-align-demo span {
        display: inline-block;
        width: 100px;
        text-align-last: justify;
    }
</style>
<ul class="zh-align-demo">
    <li><span>下载</span></li>
    <li><span>下载地址</span></li>
    <li><span>下载吧</span></li>
</ul>

文件下载(Blob)

<body>
    <button onclick="download()">文件下载</button>

    <script>
        function download(){
            const fileName= "test.txt";
            const myBlob = new Blob(["hello world"], { type: "text/plain" });
            downloadFun(fileName, myBlob);
        }
        function downloadFun(fileName, blob){
            const link = document.createElement("a");
            link.href = URL.createObjectURL(blob);
            link.download = fileName;
            link.click();
            link.remove();
            URL.revokeObjectURL(link.href);
        }
    </script>
</body>

css数据为空提示

<style type="text/css">
    .zh-value:empty:before {
        content: '--';
    }
</style>
<ul>
    <li>姓名:<span class="zh-value">张三</span></li>
    <li>昵称:<span class="zh-value"></span></li>
    <li>性别:<span class="zh-value"></span></li>
</ul>