Large collection of front-end utilities

Time:2020-1-13

Each front-end development should have its own set of tools (utils. JS), which is in line with its own development habits, and can be carried around and used out of the box. Of course, most of my works are from Baidu. Some of them are slightly modified. Share my utils.js (continuous update). Welcome to correct and supplement.

 

1. Judge JS type

JS has its own judgment method, typeof, but when it encounters a reference type, the result is often not what we want, such as

typeof []      // object   
typeof null   // object

So the custom judgment type appears

//Custom judgment element type JS
function toType(obj) {
  return Object.prototype.toString.call(obj).match(/\s+(\w+)/)[1].toLowerCase()
}

//Let's test it 
filterNull(undefined)  //'undefined'
filterNull(null)    //'null'
filterNull(NaN)    //'number'
filterNull(function(){})  //'function'
filterNull({})   //'object'
filterNull([])    //'array'
filterNull(0)    //'number'
filterNull(false)   //'boolean'

 

 

2. Filter parameters

Is there a time when the parameter returned by the background is null or undefined and then it is lost on the page, which is ugly and needs to be handled everywhere, which is not good. If you have encountered such a situation, you can use this gadget

//Parameter filter function (process parameter format parameter)
function filterNull(o) {
  for (var key in o) {
    if (o[key] === null) {
      o[key] = '/'
    }
    if (o[key] === undefined) {
      o[key] = '/'
    }
    if (toType(o[key]) === 'string' && o[key] === '') {
      o[key] = '/'
    //   debugger
    } else if (toType(o[key]) === 'object') {
      o[key] = filterNull(o[key])
    } else if (toType(o[key]) === 'array') {
      o[key] = filterNull(o[key])
    }
  }
  return o
}
//Custom judgment element type JS
function toType(obj) {
  return Object.prototype.toString.call(obj).match(/\s+(\w+)/)[1].toLowerCase()
}

3. Capture the first frame of the video

//Capture the first frame of video
//Cross domain video resources requiring background cooperation
  initialize() {
      var video, output;
      var scale = 0.8;
      var captureImage = function() {
                  var canvas = document.createElement("canvas");
                  canvas.width = video.videoWidth * scale;
                  canvas.height = video.videoHeight * scale;
                  canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
                  var img = document.createElement("img");
                  img.src = canvas.toDataURL("image/png");
                  output.appendChild(img);
      }
      Output = document.getelementbyid ("output"); // output div
      Video = document.getelementbyid ("video"); // target video to be intercepted
      Video. SetAttribute ('crossrigin ',' anonymous'); // allow cross domain
      Video. Addeventlistener ('loadaddata ', captureimage); // when the data of the previous frame is loaded, but there is not enough data to play the next frame of the specified audio / video, the loadaddata event occurs.
},

4. Intercept string based on the number of bytes

//String truncation based on bytes
    mySubString(str, len){
        Var regexp = / [^ \ X00 - \ XFF] / g; // expression matching Chinese
        //When the string byte length is less than the specified byte length
        if (str.replace(regexp, "aa").length <= len) {
        return str;
        }
        //Assume that the specified length is in Chinese
        var m = Math.floor(len/2);
        for (var i = m, j = str.length; i < j; i++) {
        //When the byte length of the intercepted string meets the specified byte length
        if (str.substring(0, i).replace(regexp, "aa").length >= len) {
        return str.substring(0, i);
        }
        }
        return str;
    }

5. JS copy to clipboard

//Input box cannot have disabled attribute
  //According to the first extension, the width and height of input cannot be 0;
  //Input box cannot have hidden attribute  

  var input = $('#input_url');
  input.select();
  document.execCommand("Copy");


  https://www.cnblogs.com/leong-min/p/6483523.html

6. REM fit font size

import Vue from 'vue'
function resizeFont() {
  var docEl = document.documentElement
  var resizeEvt = 'orientationchange' in window ? 'orientationchange' : 'resize'
  var recalc = function() {
    var clientWidth = docEl.clientWidth
    if (!clientWidth) return
    docEl.style.fontSize = 10 * (clientWidth / 360) + 'px'
  }
  if (!document.addEventListener) return
  window.addEventListener(resizeEvt, recalc, false)
  recalc()
  document.addEventListener(onload, recalc, false)
}
Vue.prototype.$resizeFont = resizeFont

7. Get the current domain name

Window. Location. Protocol + "//" + window. Location. Host; // return to https://www.cnblogs.com

Window. Location. Host; // returns the host part of the URL, for example: mp.csdn.net  
Window. Location. Hostname; // return to "www.cnblogs. Com"
Window. Location. Href; // returns the entire URL string (the complete address bar in the browser) "https://www.cnblogs.com/qqqing/p/11417738. HTML"
Window. Location. Pathname; // return / qqqing / P / 11417738.html 
Window. Location. Protocol; // returns the protocol part of the URL, such as http:, FTP:, maito:, and so on.  
The port part of window.location.port // url. If the default port 80 is used, the return value is not the default 80 but the empty character

 

8. Get the parameters in the URL

 

//Get the parameters in the URL     
 function GetQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
        Var r = window. Location. Search. Substr (1). Match (reg) // search, query? Later parameters, and match regular
        if (r != null) return unescape(r[2]); return null
   }
getUrlVars() {
    var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
    vars[key] = value;
    });
    return vars;
},