总结:常用js方法

陈发良
• 阅读 1515
函数注释
/**
 * 获取页面缓存
 * @method getSession  函数名
 * @param 参数名  字符串类型,需要获取的key名
 * @return 变量名 对象类型
 */


img.onload定义和用法
onload 事件在图片加载完成后立即执行。


判断设备
const userAgent = navigator.userAgent.toLowerCase()
const isMobile = /mobile/i.test(userAgent)
const isAndroid = /android/i.test(userAgent)
const isIOS = /iphone|ipad|ipod/i.test(userAgent)
const isWX = /MicroMessenger/i.test(userAgent)

判断是否手机号码
const isPhoneNum = num => {
  return /^1\d{10}$/.test(num)
}

对Session缓存的获取,保存,删除
const getSession = key => {
  let value = sessionStorage.getItem(key)
  if (value !== '' && value !== null) {
    return JSON.parse(value)
  }
  return {}
}
const saveSession = (key, value) => sessionStorage.setItem(key, JSON.stringify(value))
const removeSession = key => sessionStorage.removeItem(key)

对localStorage缓存的获取,保存,删除
  getLocal: key => {
    let value = localStorage.getItem(key)
    if (value !== '' && value !== null) {
      return JSON.parse(value)
    }
    return {}
  },
  saveLocal: (key, value) => localStorage.setItem(key, JSON.stringify(value)),
  removeLocal: key => localStorage.removeItem(key)


js精确计算
formatNum = function(f, digit) { 
    var m = Math.pow(10, digit); 
    return parseInt(f * m, 10) / m; 
}

生成随机32位字符
const uuid = () => {
  const S4 = () => (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1)
  return S4() + S4() + '-' + S4() + '-' + S4() + '-' + S4() + '-' + S4() + S4() + S4()
}

解析url地址
~(function (str) {
  str.queryURLParameter = function () {
    var obj = {},
      reg = /([^?=&#]+)(?:=([^?&#]+)?)/g
    this.replace(reg, function () {
      var key = arguments[1],
        value = arguments[2] || null
      obj[key] = value
    })
    return obj
  }
}(String.prototype))

 let str = window.location.search
 return str.queryURLParameter()

提高眼界:解析url地址
~function (pro) {
    pro.queryURLParameter = function () {
        var obj = {},
            reg = /([^?=&#]+)(?:=([^?=&#]+)?)/g;
        this.replace(reg, function () {
            var key = arguments[1],
                value = arguments[2] || null;
            obj[key] = value;
        });
        return obj;
    }
}(String.prototype);

var str = 'http://www.zhufengpeixun.cn/stu/?lx=1&name=&sex=#teacher';
console.log(str.queryURLParameter());


动态生成标签,如script,iframe标签等
function inject (container, src, tag = 'iframe') {
  let context = document.createElement(tag)
  context.id = 'i-' + new Date().getTime()
  if (tag === 'link') {
    context.href = src
    context.rel = 'stylesheet'
  } else {
    context.src = src
  }
  document.querySelectorAll(container)[0].appendChild(context)
  return new Promise((resolve, reject) => {
    if (context.readyState) {
      context.onreadystatechange = () => {
        if (this.readyState == 'loaded' || this.readyState == 'complete') {
          this.onreadystatechange = null
          resolve(context)
        }
      }
    } else {
      context.onload = () => resolve(context)
    }
  })
}

提示语:
function showMsg (txt = '', Autoclose = true) {
  if (txt == '') {
    return false // 为空则不弹出
  }
  let msg = document.createElement('div')
  msg.innerHTML = `
        <div className="msg" style="
        position: fixed;
        left:50%;
        top:50%;
        transform: translate(-50%,-30%);
        font-size: 0.28rem;
        padding: 0.2rem 0.3rem;
        border-radius: 0.08rem;
        background: rgba(0, 0, 0, 0.8);
        line-height: 1.5;
        max-width: 4rem;
        color: #fff;
        word-break:break-all;
        max-height:4rem;
        overflow-x:auto;
        z-index:9999999";
        id="show_tip">
            ${txt}
        </div>
    `
  document.body.appendChild(msg)
  if (Autoclose) {
    setTimeout(() => {
      document.body.removeChild(msg)
    }, 3000)
  } else {
    document.getElementById('show_tip').parentNode.onclick = function () {
      document.body.removeChild(msg)
    }
  }
}

等待的显示和隐藏
function loadingCom () {
  let loadingElent = document.createElement('div')
  let att = loadingElent.setAttribute('class', 'loading')
  let attId = loadingElent.setAttribute('id', 'loading')
  loadingElent.innerHTML =
    `
    <div class="params" style="width:100%;height:100%;position: fixed;background:rgab(0,0,0,.3);">
    <div class="loading-com" style="
    width:1.25rem;
    height:1.25rem;
    top:50%;
    left: 50%;
    margin-left:-.625rem;
    margin-top:-.605rem;
    position: absolute;">
      <img src="https://h5game.gowan8.com/static/img/loading.gif" width="100%">
    </div>
  </div>
  `
  document.body.appendChild(loadingElent)
}

function removeLoading () {
  var loading = document.getElementById('loading')
  document.body.removeChild(loading)
}


// 合并对象方法
const assign = Object.assign || function (t) {
  // 合并参数
  let n = arguments.length, s
  for (let i = 1; i < n; i++) {
    s = arguments[i]
    for (var p in s) {
      if (Object.prototype.hasOwnProperty.call(s, p)) {
        t[p] = s[p]
      }
    }
  }
  return t
}

// 判断是否是空对象
function isEmptyObject (obj) {
  var name
  for (name in obj) {
    return false
  }
  return true
}


//设置cookie
function setCookie(name,value){
    if(!name||!value) return;
    var Days = 30;//默认30天
    var exp  = new Date();
    exp.setTime(exp.getTime() + Days*24*60*60*1000);
    document.cookie = name + "="+ encodeURIComponent(value) +";expires="+ exp.toUTCString();
}

//获取cookie
function getCookie(name){
    var arr = document.cookie.match(new RegExp("(^| )"+name+"=([^;]*)(;|$)"));
    if(arr != null) return decodeURIComponent(arr[2]);
    return null;
}

//删除cookie
function delCookie(name){
    var exp = new Date();
    exp.setTime(exp.getTime() - 1);
    var cval=getCookie(name);
    if(!cval) document.cookie=name +"="+cval+";expires="+exp.toUTCString();
}



jQuery中对cookie的操作
jQuery.cookie = function (name, value, options) {
  if (typeof value != 'undefined') { // name and value given, set cookie //2个参数设置cookie 
      options = options || {};
      if (value === null) {
          value = '';
          options.expires = -1;
      }
      var expires = '';
      if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
          var date;
          if (typeof options.expires == 'number') {
              date = new Date();
              date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
          } else {
              date = options.expires;
          }
          expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
      }

      var path = options.path ? '; path=' + (options.path) : '';
      var domain = options.domain ? '; domain=' + (options.domain) : '';
      var secure = options.secure ? '; secure' : '';
      document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
  } else { // only name given, get cookie  //一个参数,读取cookie  
      var cookieValue = null;
      if (document.cookie && document.cookie != '') {
          var cookies = document.cookie.split(';');
          for (var i = 0; i < cookies.length; i++) {
              var cookie = cookies[i].trim();
              // Does this cookie string begin with the name we want?
              if (cookie.substring(0, name.length + 1) == (name + '=')) {
                  cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                  break;
              }
          }
      }
      return cookieValue;
  }
}




switch case 用法
switch (op_type) {
                    case 0:
                      that._customerService(paycbData, callback)
                      break;
                    case 1:
                      that._requestMidasPayment(dataFormidashi, paycbData, callback)
                      break;
                    case 2:
                      that._requestMidasPayment(dataFormidashi, paycbData, callback)
                      break;
                    case 3:
                      break;
                    case 4:
                      break;
                    case 5:
                      that._payCallback(paycbData, callback) //直接回调
                      break;
                  }




全局配置url方法根据不同域名设置不同的模式,请求不同的地址
let ENV = 'local'
if (/gowanme/.test(location.hostname)) ENV = 'test'
if (/demo/.test(location.hostname)) ENV = 'dev'
if (/gowan8\.com/.test(location.hostname)) ENV = 'prod'
const __gowanpayDomain = {
  local: 'pay.gowanme.com',
  dev: 'pay.gowanme.com',
  test: 'pay.gowanme.com',
  prod: 'pay.gowan8.com',
  get () {
    return `//${__gowanpayDomain[ENV]}/`
  }
}


 微信内部H5支付(得到后台给的参数,发起支付即可)
      function wxpay (config) {
        FN.log('wxpay:', config)
        let {
          appId,
          timeStamp,
          nonceStr,
          signType,
          paySign,
          redirectUrl
        } = config
        WeixinJSBridge.invoke(
          'getBrandWCPayRequest',
          {
            appId, // 公众号名称,由商户传入
            timeStamp, // 时间戳,自1970年以来的秒数
            nonceStr, // 随机串
            package: config.package,
            signType, // 微信签名方式:
            paySign // 微信签名
          },
          function (res) {
            if (res.err_msg === 'get_brand_wcpay_request:ok') {
              FN.log('执行微信支付成功', res)
            }
          }
        )
      }


第三方浏览器直接打开app。
安卓:
var state = null;
try {
    if (scheme != '') {
        openIframe.src = '【scheme】://【host】/【openwith】';
    }
} catch (e) { }
if (state) {
    window.close();
} else {
    location.href='下载地址';   
}

苹果:
if (scheme != '') {
    window.location.href = '【scheme】://';
}


判断是不是一个函数
typeof (this.confirmModalOptions.btnSubmitFunction) === 'function'

抛出异常
 throw Error('err:show不存在')


技巧
当某些值需要进行传递是,可以将值挂载在window上,然后再另外一个地方,通过window进行获取


正则匹配数组或者使用任意符号包裹起来的内容
   const str2 = strs
   const reg = /\[(.+?)\]/g
   str2.match(reg)
例如:
正则匹配指定<>括号内的内容,并进行删除
// 对model进行处理
function handlerModel(str=''){
  const reg = /\<(.+?)\>/g
  if (str.match(reg)){
    let delStr = s.match(reg)[0]
    return s.replace(delStr, '')
  }
}



js删除节点
var theParent = document.getElementById("bq_ly");  
theParent.parentNode.removeChild(theParent);







/**
 * 验证是否有空格
 *
 * @param {}
 *            source
 */
function checkSpace(source) {
    var regex = /\s/g;
    return regex.test(source);
}


/**
 * 随机数UUID
 * @return
 */
function makeUUID() {
    var S4 = function () {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
}





获取对象的键名,返回值是一个数组
Object.keys(obj)

获取对象的值,返回值是一个数组
Object.values(obj)

从一个对象中获取选中的键和值,返回一个新对象
Object.select(obj, ['name', 'phone'])
第一个参数obj,是需要选取的目标对象,第二个参数是一个数组。是具体需要获取的值

把一个对象中,所有属性的值都清空
object.clear(obj)

发布订阅
先订阅,再发布
window.__subscribe = {}
window.__subscribe['make_order'] = function () {
   _this._makeOrder(token, args)
 }
在需要发布的地方发布,订阅案例
if (window.__subscribe['make_order']) {
   window.__subscribe['make_order']()
   delete window.__subscribe['make_order']
 }

理解:就是给window的__subscribe对象绑定一个方法,在需要用到的地方,执行该方法,
执行完成后,再删除该方法

额外理解,
1 就是当执行某个方法的时候,能执行里面所有的方法
2 里面所有的方法是一个数组,遍历得到这个数组,并进行执行
3 数组里面的方法来自一个对象,这个对象可以生成很多个数组方法,可以参考用工厂模式



工厂模式:
所谓的工厂模式,就是一个方法,通过传入不同的参数,返回不同的方法, 或者对象,这个模式称为工厂模式,出来的产品都是一样的,所以是工厂模式
例子:
function(a,b,){
if(a=='xxx'){
return obja
}
if(b=='xxx){
return objb
}
}


 js调用App 方法
假设方法名为  JAMS__mark
android 系统:
  window.android.JAMS__mark(params)   // @params为传入的参数, app内可以收到
ios 系统:  
         window.webkit.messageHandlers.JAMS__mark.postMessage(params)   // @params为传入的参数, app内可以收到

封装后为:
export function JAMS__mark() {
    if (/android/i.test(navigator.userAgent)) {
        try {
            window.android.JAMS__mark(params)
        } catch (e) {
            console.log(e)
        }
    } else if (/ios|iphone|ipod|pad/i.test(navigator.userAgent)) {
        try {
            window.webkit.messageHandlers.JAMS__mark.postMessage(params)
        } catch (e) {
            console.log(e)
        }
    }
}


App调用js方法
App调用js 方法需要js将方法挂载在window下,这样App才能调用到方法,
假设方法名叫    JAMS__success
window.JAMS__success = function () {
  // do some thing
  // if need some params ,you can alse return it
  return params;
}


解决正则 /g 全局匹配替换问题
我要用 JS 替换一个多行文本的关键字
正常,没有变量的时候应该是这样:
把 a 替换成 b:
string.replace("a","b");
以上只能替换第一个匹配的,要全文匹配应该用正则表达式:
string.replace(/a/g,"b");
正则加个参数 g ,表示全文匹配。

但现在,我要替换的不是 a 这个字符了,而是从外面传进来的一个变量:
var key;
我可以这么写:
string.replace(key,"b");
这只能替换第一个匹配的,要全文匹配就遇到难题了:
string.replace(/key/g,"b");
这样写是不行的,变量 key 传不到正则里面去。。。头疼啊

解决方法:
string.replace(new RegExp(key,'g'),"b");

例子
var text = "饿~,23333。饿~,测试yongde"
    var word = "饿~"
    var newWorld = "额~~eeeee"
    // text = text.replace(word, newWorld)// 只能替换第一个
    text = text.replace(new RegExp(word, 'g'), newWorld); // 全局替换
    console.log(text,'我是text')


正则判断是否存在某个特定字符串的方法
var handleBaseApi = function() {
  var host = location.host
  var regDev = RegExp(/gowanme/)
  var regPro = RegExp(/gowan8/)
  if (regDev.test(host)) {
    baseApi = 'http://game.gowanme.com/'
  } else if (regPro.test(host)) {
    baseApi = 'http://game.gowan8.com/'
  }
}
handleBaseApi()



vue 传值赋值
 this.$router.push({name: 'vipDetails', query: {data: JSON.stringify(obj)}})
 this.imgSrc = JSON.parse(this.$route.query.data).detailsSrc

路由跳转有r,获取连接参数没有r

微信跳转问题
微信下不能用window.open('....');
能用location.href = ''; 




/**
 * 封装ajax请求
 * @param {} option字段 
 * url
 * data
 * method
 * success
 * error
 */
var requestApi = function (option = {}) {

  var defaults = {
    method: 'POST',
    data: {},
    success: function (data) {

    },
    error: function (status) {

    },
    dataType: 'json',
    async: true
  }
  var option = __assign(defaults, option);
  option.method = option.method.toUpperCase()
  var formData = []
  for (var key in option.data) {
    formData.push(''.concat(key, '=', option.data[key]))
  }
  option.data = formData.join('&')

  var xhr = new XMLHttpRequest()
  xhr.onreadystatechange = function () {
    if (xhr.readyState === 4 && xhr.status === 200) {
      let data = xhr.responseText
      try {
        if (option.dataType == 'json') {
          data = JSON.parse(data)
        }
        option.success(data)
      } catch (e) {
        console.log(logObj(e), '===>ajax错误信息')
        option.error(xhr.status)
      }
    } else {
      option.error(xhr.status)
    }
  }
  xhr.open(option.method, option.url, option.async)
  if (option.method === 'POST') {
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=utf-8')
  } else {
    option.url = option.url + (option.url.indexOf('?') >= 0 ? "&" : "?") + option.data
  }
  xhr.send(option.method === 'POST' ? option.data : null)
}



//封装jsonp请求
function jsonp(obj) {

  var defaults = {
    data: {},
    success: function (data) {},
    error: function () {},
    timeout: 10000
  }
  obj.data = obj.data || '';
  if (typeof obj.data == 'object') {
    var arr = new Array();
    for (var key in obj.data) {
      arr.push(key + '=' + obj.data[key])
    }
    obj.data = arr.join('&');
  }
  let clearJsonp = function (id) {
    window[id] = undefined;
  }
  let removeScript = function (id) {
    document.body.removeChild(document.getElementById(id));
  }
  var obj = __assign(defaults, obj);
  //写入url地址中的函数名称,动态创建
  var id = 'jsonp_' + Date.now() + Math.random().toString().substr(2, 5);

  //创建一个script标签
  var script = document.createElement("script");
  script.id = id;

  //设置标签的请求路径
  //像这样:http://localhost:3000/api?callback=jsonp_callback_153498520409635392&id=1
  script.src = obj.url + (/\?/.test(obj.url) ? '&' : '?') + 'callback=' + id + '&' + obj.data;

  var timeoutId = setTimeout(function () {
    clearJsonp(id);
    removeScript(id);
    obj.error();
  }, obj.timeout);

  //将创建好的带请求的script标签添加到html的body中
  document.body.appendChild(script);

  //这里必须这样写window[callbackName];
  //如果写window.callbackName会报错没有定义
  window[id] = function (res) {
    obj.success(res);
    //删除的时候可以这样写
    //由于请求一次会创建一个script标签和一个函数,所以每次获取到结果后就删除
    clearTimeout(timeoutId);
    clearJsonp(id);
    removeScript(id);
  }
}


用法:
jsonp({
url:'xx',
data:{},
success:function(res){
console.log(res,'后端的返回值')
}
})









/**
 * 分割IP地址
 *
 * @param {}
 *            ipAddress
 */
function getIpNum(ipAddress) {
    var ip = ipAddress.split(".");
    var a = parseInt(ip[0]);
    var b = parseInt(ip[1]);
    var c = parseInt(ip[2]);
    var d = parseInt(ip[3]);
    var ipNum = a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
    return ipNum;
}

/**
 * 判断IP大小
 */
function decideIp(startIp, endIp) {
    var ip1 = getIpNum(startIp);
    var ip2 = getIpNum(endIp);
    return (ip2 > ip1) ? true : false;
}


/*******************************************************************************
 * openWindow(url)函数:弹出窗口 * url:路径 * left:左边的距离 * top:上边的距离 * width:窗口宽度 *
 * height:窗口高度 * resize:yes时可调整窗口大小,no则不可调 *
 ******************************************************************************/
function openWindow(url,width, height, resize) {
    var mleft = (screen.width - width) / 2;
    var mtop = (screen.height - height) / 2;
    window.open(url,"","height=" + height + ",width=" + width
        + ",location=no,menubar=no,resizable=" + resize
        + ",scrollbars=yes,status=no,toolbar=no,left=" + mleft
        + ",top=" + mtop + "");
}

function openWindow(url,width, height, resize,scrollbars) {
    var mleft = (screen.width - width) / 2;
    var mtop = (screen.height - height) / 2;
    window.open(url,"","height=" + height + ",width=" + width
        + ",location=no,menubar=no,resizable=" + resize
        + ",scrollbars="+scrollbars+",status=no,toolbar=no,left=" + mleft
        + ",top=" + mtop + "");
}
/**
 *
 * @param {} url
 * @param {} width
 * @param {} height
 */
function showNewWind(url,width,height){
    //alert(url);
    var showresult = window.showModalDialog(url,window,"dialogWidth="+width+"px;dialogHeight="+height+"px;location=no;status=no;scroll=yes");
    return showresult;
}

/**
 *
 * @param {} url
 * @param {} width
 * @param {} height
 */
function showNewLessWind(url,width,height){
    //alert(url);
    var showresult = window.showModelessDialog(url,window,"dialogWidth:"+width+"px;location=no;status:no;dialogHeight:"+height+"px");
    return showresult;
}

function decideLeve(source){
    var regex=/^[a-zA-Z]{1}$/g;
    return regex.test(source);
}

function openBlankWindow(url){
    openWindow(url,"650","400","yes");
}


/**
 验证身份证号是否正确
 **/
function isCardNo(num){
    if(isNaN(num)){
        alert("输入的身份证号不是数字!");
        return false;
    }
    var len = num.length;
    if(len<15 || len>18){
        alert("输入的身份证号码长度不正确定!应为15位或18位");
        return false;
    }
    var re15 = /^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$/;
    var re18 = /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/;
    var res = (re15.test(num) || re18.test(num));
    if(res==false){
        alert("输入的身份证号格式不正确!");
        return false;
    }
    return res;
}






/**
 生成指定位数的随机整数
 **/
function getRandomNum(count){
    var arr = new Array;
    var reNum = "";
    for(var i=0;i<count;i++){
        arr[i] = parseInt(Math.random()*10);
        reNum += String(arr[i]);
    }
    return reNum;
}
function random(min,max){
    return Math.floor(min+Math.random()*(max-min));
}


/*
 *判断包含关系
 *string:原始字符串
 *substr:子字符串
 *isIgnoreCase:忽略大小写
 */
function jsContains(string,substr,isIgnoreCase)
{
    if(isIgnoreCase)
    {
        string=string.toLowerCase();
        substr=substr.toLowerCase();
    }
    var startChar=substr.substring(0,1);
    var strLen=substr.length;
    for(var j=0;j<string.length-strLen+1;j++)
    {
        if(string.charAt(j)==startChar)//如果匹配起始字符,开始查找
        {
            if(string.substring(j,j+strLen)==substr)//如果从j开始的字符与str匹配,那ok
            {
                return true;
            }
        }
    }
    return false;
}

/**
 * 随机数UUID
 * @return
 */
function makeUUID() {
    var S4 = function () {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    //return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
    return (S4() + S4() + S4() + S4() + S4() + S4() + S4() + S4());
}






/**
 *  显示提示信息
 * @param {Object} msg
 */
function showInfoMessage(msg) {
    Ext.MessageBox.show({
        width:320,
        buttons:Ext.Msg.OK,
        msg:msg,
        icon:Ext.MessageBox.INFO,
        title:"系统提示"
    });
}

/**
 * 给URL追加参数
 * @param {} url
 * @param {} parameter 参数名
 * @param {} value  参数值
 */
function urlAddParmert(url,parameter,value){
    var buf = new StringBuffer();
    if(!isEmpty(url)){
        buf.append(url);
        if(url.indexOf("?") > -1){  //已经有参数
            buf.append("&");
        }else{
            buf.append("?");
        }
        buf.append(parameter);
        buf.append("=");
        buf.append(value);
    }
    return buf.toString();
}

/**
 * 得到文件的扩展名
 * @param {} filename
 */
function getFileExt(filename){
    var d=/\.[^\.]+$/.exec(filename);
    var ext = new String(d);
    var s = ext.toLowerCase();
    return s;
}


//字符串编码
function strEncode(source){
    return encodeURIComponent(source);
}

//字符串解码
function strDencode(source){
    return decodeURIComponent(source);
}








监控路由
 watch: {
    $route: function(to, from) {
      // 拿到目标参数 to.query.id 去再次请求数据接口
      // console.log(to, from, 'from')
      this.proData.article_type = to.query.article_type
      this.proData.article_id = to.query.article_id
      this.get()
    }
  },



 // 基于服务器时间的倒计时--
注意 1 nowtime需要设置为全局变量,2 isGetTime 表示是否得到了服务器时间
  // 处理服务器时间
  handletime(time) {
    if (this.data.isGetTime) {
      return this.data.nowtime += 1000
    } else {
      this.data.nowtime = new Date(time).getTime()
      this.data.isGetTime = true
      return this.data.nowtime
    }
  },

  // 倒计时
  countdown: function () {
    var nowtime = this.handletime("2020/10/8"),
      endtime = new Date("2020/10/28"); //定义结束时间

    var lefttime = endtime.getTime() - nowtime, //距离结束时间的毫秒数
      leftd = Math.floor(lefttime / (1000 * 60 * 60 * 24)), //计算天数
      lefth = Math.floor(lefttime / (1000 * 60 * 60) % 24), //计算小时数
      leftm = Math.floor(lefttime / (1000 * 60) % 60), //计算分钟数
      lefts = Math.floor(lefttime / 1000 % 60); //计算秒数
    leftd = leftd < 10 ? '0' + leftd : leftd
    lefth = lefth < 10 ? '0' + lefth : lefth
    leftm = leftm < 10 ? '0' + leftm : leftm
    lefts = lefts < 10 ? '0' + lefts : lefts
    return {
      leftd,
      lefth,
      leftm,
      lefts
    }
  },


setInterval(() => {
      var time = this.countdown()
      this.setData({
        timeObj: time
      })
    }, 1000)



基于本地时间的倒计时
var showtime = function () {
   var nowtime = new Date(),  //获取当前时间
       endtime = new Date("2020/8/8");  //定义结束时间
   var lefttime = endtime.getTime() - nowtime.getTime(),  //距离结束时间的毫秒数
      leftd = Math.floor(lefttime/(1000*60*60*24)),  //计算天数
       lefth = Math.floor(lefttime/(1000*60*60)%24),  //计算小时数
        leftm = Math.floor(lefttime/(1000*60)%60),  //计算分钟数
        lefts = Math.floor(lefttime/1000%60);  //计算秒数
    return leftd + "天" + lefth + ":" + leftm + ":" + lefts;  //返回倒计时的字符串
}

var div = document.getElementById("showtime");
setInterval (function () {
   div.innerHTML = showtime();
}, 1000);  //反复执行函数本身



验证码倒计时的实现
dom:
 <span  v-show="show" @click="getCode" class="code-txt">获取验证码</span>
          <span  v-show="!show" class="code-txt count">{{count}} 秒</span>

data:
 show: true,
      count: '',
      timer: ''

methods:
 // 获取验证码
    getCode () {
      const TIME_COUNT = 60
      if (!this.timer) {
        this.count = TIME_COUNT
        this.show = false
        this.timer = setInterval(() => {
          if (this.count > 0 && this.count <= TIME_COUNT) {
            this.count--
          } else {
            this.show = true
            clearInterval(this.timer)
            this.timer = null
          }
        }, 1000)
      }
    },


数组map方法

 map() 方法返回一个由原数组中的每个元素调用一个指定方法后的返回值组成的新数组。



// 原生js实现复制内容到剪切板,兼容pc、移动端(支持Safari浏览器)
    copyText () {
      if (typeof document.execCommand !== 'function') {
        FN.showMsg('复制失败')
        return
      }
      if (!document.createRange) {
        // pc,安卓
        var dom = document.getElementById('copy-qq')
        dom.select()
        var result = document.execCommand('copy')
        if (result) {
          FN.showMsg('复制成功')
        }
      } else {
        // 苹果端
        var range = document.createRange()
        var idom = document.getElementById('copy-qq')
        range.selectNode(idom)
        const selection = window.getSelection()
        if (selection.rangeCount > 0) {
          selection.removeAllRanges()
        }
        selection.addRange(range)
        document.execCommand('copy')
        FN.showMsg('复制成功')
      }
    }


提取字符串中的数字
var s ="价格4500元";
var num= s.replace(/[^0-9]/ig,"");
alert(num);//4500


vue中需要给element的函数,添加参数时,可以使用bind进行绑定添加



点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Karen110 Karen110
2年前
一篇文章带你了解JavaScript日期
日期对象允许您使用日期(年、月、日、小时、分钟、秒和毫秒)。一、JavaScript的日期格式一个JavaScript日期可以写为一个字符串:ThuFeb02201909:59:51GMT0800(中国标准时间)或者是一个数字:1486000791164写数字的日期,指定的毫秒数自1970年1月1日00:00:00到现在。1\.显示日期使用
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Wesley13 Wesley13
2年前
JS中有趣的知识
1.分号与换行functionfn1(){return{name:'javascript'};}functionfn2(){return{name:'javascript'
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Wesley13 Wesley13
2年前
mysql设置时区
mysql设置时区mysql\_query("SETtime\_zone'8:00'")ordie('时区设置失败,请联系管理员!');中国在东8区所以加8方法二:selectcount(user\_id)asdevice,CONVERT\_TZ(FROM\_UNIXTIME(reg\_time),'08:00','0
Stella981 Stella981
2年前
JS 对象数组Array 根据对象object key的值排序sort,很风骚哦
有个js对象数组varary\{id:1,name:"b"},{id:2,name:"b"}\需求是根据name或者id的值来排序,这里有个风骚的函数函数定义:function keysrt(key,desc) {  return function(a,b){    return desc ? ~~(ak
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这
陈发良
陈发良
Lv1
如需要外包,请加我微信chenfaliang1995
文章
4
粉丝
1
获赞
8