前端实用工具大集合

每一个前端开发都应该有属于自己的一套工具(utils.js),符合自己的开发习惯,随身携带,开箱即用。当然我的大多数是摘自百度,有的稍加修改,分享一下我的utils.js(持续更新),欢迎大家指正补充。

 

1.判断js类型

 js有自己判断方法 typeof 但是当他遇到引用类型的时候得到的结果往往不是我们想要的,例如

typeof []      // object   
typeof null   // object

于是自定义判断类型就出现了

// 自定义判断元素类型JS
function toType(obj) {
  return Object.prototype.toString.call(obj).match(/\s+(\w+)/)[1].toLowerCase()
}

//来我们测试一下 
filterNull(undefined)  //'undefined'
filterNull(null)    //'null'
filterNull(NaN)    //'number'
filterNull(function(){})  //'function'
filterNull({})   //'object'
filterNull([])    //'array'
filterNull(0)    //'number'
filterNull(false)   //'boolean'

 

 

2.过滤参数

有没有时候后台返回的参数是null或者undefined然后就被丢到了页面上,很难看,要每一个地方都去处理,很不好,如果你也遇到过这样情况,那么你就可以用到这个小工具啦

// 参数过滤函数(处理参数 格式化参数)
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
}
// 自定义判断元素类型JS
function toType(obj) {
  return Object.prototype.toString.call(obj).match(/\s+(\w+)/)[1].toLowerCase()
}

 3.截取视频第一帧

//截取视频第一帧
//需要后台配合视频资源的跨域
  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");  //输出的div
      video = document.getElementById("VIDEO");    //要截取的目标video
      video.setAttribute('crossorigin', 'anonymous');  //允许跨域
      video.addEventListener('loadeddata',captureImage); //当当前帧的数据已加载,但没有足够的数据来播放指定音频/视频的下一帧时,会发生 loadeddata 事件。
},

4.根据字节数截取字符串

    //根据字节截取字符串
    mySubString(str, len){
        var regexp = /[^\x00-\xff]/g;// 正在表达式匹配中文
        // 当字符串字节长度小于指定的字节长度时
        if (str.replace(regexp, "aa").length <= len) {
        return str;
        }
        // 假设指定长度内都是中文
        var m = Math.floor(len/2);
        for (var i = m, j = str.length; i < j; i++) {
        // 当截取字符串字节长度满足指定的字节长度
        if (str.substring(0, i).replace(regexp, "aa").length >= len) {
        return str.substring(0, i);
        }
        }
        return str;
    }
    

5.js复制到剪切板

  //input框不能有disabled属性
  // 根据第一条扩展,input的width || height 不能为0;
  //input框不能有hidden属性  
<input id='input_url' v-model='product_url' style='opacity: 0;position: absolute;' type="text">
  var input = $('#input_url');
  input.select();
  document.execCommand("Copy");


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

6.rem适配字体大小

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.获取当前域名

window.location.protocol+"//"+window.location.host; //   返回https://www.cnblogs.com

window.location.host; //返回url 的主机部分,例如:mp.csdn.net  
window.location.hostname; //返回"www.cnblogs.com
window.location.href; //返回整个url字符串(在浏览器中就是完整的地址栏)   "https://www.cnblogs.com/Qqqing/p/11417738.html"
window.location.pathname; //返回 /Qqqing/p/11417738.html 
window.location.protocol; //返回url 的协议部分,例如: http:,ftp:,maito:等等。  
window.location.port //url 的端口部分,如果采用默认的80端口,那么返回值并不是默认的80而是空字符  

 

 8.获取url里的参数

 

//获取url里的参数     
 function GetQueryString(name) {
        var reg = new RegExp('(^|&)' + name + '=([^&]*)(&|$)')
        var r = window.location.search.substr(1).match(reg)// search,查询?后面的参数,并匹配正则
        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;
},

 

posted @ 2019-08-27 13:17  Q_Qing  阅读(696)  评论(0编辑  收藏  举报