工具方法

滚动到元素顶部

document.querySelector(el).scrollTo(0, 0)

获取协议

const protocol = window.location.protocol

将table导出为xlsx

import FileSaver from 'file-saver'
import XLSX from 'xlsx'

        // /* generate workbook object from table */
        // // 转换成excel时,使用原始的格式
        let xlsxParam = {raw: true};
        // el-table的fixed属性来让某一列固定,但elementui的实现方式是:创建了两个tabledom,通过一个隐藏一个显示来实现交互效果。
        // 当导出整个el-table 就会将两个div内的table都导出,导致数据重复。移除重复table
        let fix = document.querySelector('.el-table__fixed');
        let wb;
        if (fix) {
          wb = XLSX.utils.table_to_book(document.querySelector('.el-table').removeChild(fix), xlsxParam);
          document.querySelector('.el-table').appendChild(fix);
        } else {
          wb = XLSX.utils.table_to_book(document.querySelector('.el-table'), xlsxParam);
        }

        /* get binary string as output */
        let wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'array'});
        try {
          FileSaver.saveAs(new Blob([wbout], {type: 'application/octet-stream'}), '差评查询-' + (moment(new Date()).format('YYYYMMDD')) + '.xlsx');
        } catch (e) {
          if (typeof console !== 'undefined') {
            console.log(e, wbout)
          }
        } finally {
          this.isExport = false;
          this.pageSize = pageSize
        }
        return wbout;

数组对象去重

// 数组对象去重
        let hash = {};
        this.targetList = this.targetList.reduce(function (item, next) {
          hash[next.name] ? '' : hash[next.name] = true && item.push(next);
          return item
        }, [])

数组拼接

let arr = [1, 2];
arr.push(...[3, 4]);

正则方法

      let re = /\/p\/(.*?).html/
      let str = 'https://wwww.badu.com/p/121212.html'
      // 121212
      console.log(str.match(re)[1])

      // 121212
      console.log(re.exec(str)[1])

      // true
      console.log(re.test(str))

      // 匹配到的起始位置  -1为没匹配到
      console.log(str.search(re))

      // 替换
      console.log(str.replace(re, '/p/686868.html'))
千分位格式化
    format(num) {
      // let reg = /(\d)(?=(\d{3})+(?!\d))/g
      let reg = /\d{1,3}(?=(\d{3})+$)/g
      return (num + '').replace(reg, '$&,')
    }

 使用过滤器

// 百分百公共方法
Vue.filter('toPercent', function (val) {
  return (val * 100).toFixed(2) + '%'
});
// 千分位公共方法
Vue.filter('thousands', function (val) {
  // let reg = /(\d)(?=(\d{3})+(?!\d))/g
  let reg = /(\d{1,3})(?=(\d{3})+(?:$|\.))/g;
  let result = (val + '').replace(reg, '$&,'); return result });

页面上

    {{ 0.33333 | toPercent() }}
    {{ 9999999 | thousands() }}

 其他

// echarts重绘
    reDraw(id) {
      document.getElementById(id).removeAttribute('_echarts_instance_')
    },
    // 只能输入整数和小数
    AllowDigitalDecimal(val) {
      let reg = /^\d+(\.\d{0,2})?$/g
      if (reg.test(val)) {
        return false
      } else {
        return true
      }
    },
    // 只能输入数字
    AllowDigital(val) {
      let reg = /[^\d]/g;
      if (reg.test(val)) {
        this.$message({
          message: '只能输入数字',
          type: 'warning'
        });
      }
      let result = val.replace(reg, '');
      return result
    },
    // 不允许空格
    NoSpacesAllowed(val) {
      let reg = /\s+/g;
      let result = val.replace(reg, '');
      return result
    },
    // 判断不能为空
    IsEmpty(val) {
      let reg = /\s+/g;
      if (reg.test(val) || val === null || val.length === 0) {
        return false
      } else {
        return true
      }
    },
    // 汉字长度限制为1-50个
    Limit(val) {
      // 匹配中文,英文字母和数字及_
      let reg = /^[\u4e00-\u9fa5_a-zA-Z0-9]{1,50}$/g;
      if (reg.test(val)) {
        return true
      } else {
        return false
      }
    }

 路由跳转

// 字符串
this.$router.push('/home/first')
// 对象
this.$router.push({ path: '/home/first' })
// 命名的路由
this.$router.push({ name: 'home', params: { userId: wise }})
// 点击事件里面写
this.$router.push({ name: 'distributesList', query: { ruleForm: this.ruleForm }})
router-link
查询字符串:
去哪里 ?
<router-link :to="{name:'detail',query:{id:1}}"> xxx </router-link> 导航(查询字符串path不用改) {name:'detail',path:'/detail',组件} 去了干嘛?获取路由参数(要注意是 query ,还是 params 和 对应的 id 名? 是后者需要注意设置相关文件的id规则) + this.$route.query.id
path方式:
去哪里 ?
<router-link :to="{name:'detail',params:{name:1}}"> xxx </router-link> 导航(查询字符串path不用改) {name:'detail',path:'/detail/:name',组件} 去了干嘛?获取路由参数(要注意是 query ,还是 params 和 对应的 name 名? 是后者需要注意设置相关文件的id规则) + this.$route.params.id

页面不刷新情况下修改url参数

window.history.pushState(data, title, targetURL);
@状态对象:传给目标路由的信息,可为空
@页面标题:目前所有浏览器都不支持,填空字符串即可
@可选url:目标url,不会检查url是否存在,且不能跨域。如不传该项,即给当前url添加data
window.history.replaceState(data, title, targetURL);
@类似于pushState,但是会直接替换掉当前url,而不会在history中留下记录

打开新窗口

<router-link tag="a" target="_blank" :to="{name:'searchGoods',params:{catId:0},query:{keywords:'手机'}}">热门好货</router-link>
let routeData = this.$router.resolve({
   name: "searchGoods",
   query: params,
   params:{catId:params.catId}
});
window.open(routeData.href, '_blank');

 

<a class="target" href="" target="_blank"></a>
      let target = document.querySelector('.target')
      target.setAttribute('href', window.location.origin + '/home/integral-record')
      target.click()

json排序

desc (x,y) {
    return (x['index'] < y['index']) ? 1 : -1
},
asc(x, y) {
    return (x['index'] > y['index']) ? 1 : -1
},
let k = [
{
index: 13,
name: 'e'
},
{
index: 1,
name: 'a'
}
]
console.log(k.sort(this.asc))
 

字符串 to JSON

      this.sign = eval('(' + res.data.data + ')') // 将json字符串转换成json对象
      this.sign = JSON.parse(res.data.data); // 将json字符串转换成json对象
      this.sign = JSON.stringify(res.data.data); // 将json对象转换成json对符串

对象是否为空

let objLength = Object.keys(val)
if (objLength.length !== 0) {
}

数组、字符串互转

var a, b;
a = new Array(0,1,2,3,4);
b = a.join("-");      //"0-1-2-3-4"
var s = "abc,abcd,aaa";
ss = s.split(",");// 在每个逗号(,)处进行分解  ["abc", "abcd", "aaa"]
var s1 = "helloworld";
ss1 = s1.split('');  //["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"]

一个子组件循环渲染

<div class="db" v-for="(item,index) in this.allData" :key="item.reviewType">
      <router-link :to="{path:'/analysis/'+ item.reviewType}">
        <div class="title">
          {{item.reviewType}}
          <i class="el-icon-arrow-right icon-right"></i>
        </div>
      </router-link>
      <show-data :id="'show'+index" :trend="item.trend"></show-data>
    </div>

子组件

<div :id="this.id" style="width: 96%;height: 220px;margin: 0 auto"></div>

 数组大小比较方法

let one = Math.max.apply(null, arr1)
let two = Math.max.apply(null, arr2)
let max = Math.max(one, two) + Math.max(one, two) / 2

 H5页面流畅滚动

  #wrap ul {
    overflow-x: hidden;
    overflow-y: scroll;
    -webkit-overflow-scrolling: touch;
  }

滚动条样式

  /*滚动条样式*/
  ::-webkit-scrollbar {
    width: 8px;
    height: 8px;
    background-color: transparent;
  }

  ::-webkit-scrollbar-thumb {
    border-radius: 2px;
    background: rgba(0, 0, 0, .2);
  }

当月第一和最后一天

      let now = new Date() //当前日期
      let nowMonth = now.getMonth() //当前月
      let nowYear = now.getFullYear() //当前年
      //本月的开始时间
      let monthStartDate = new Date(nowYear, nowMonth, 1)
      //本月的结束时间
      let monthEndDate = new Date(nowYear, nowMonth + 1, 0)
      console.log('本月1号是' + new Date(monthStartDate))
      console.log('本月最后一天是' + new Date(monthEndDate))

      new Date(new Date().getFullYear(), new Date().getMonth() - 1, 1)  // 上月1号 
      new Date(new Date().getFullYear(), new Date().getMonth(), 1)   // 当前月1号
// 获得当前年份4位年
        let currentYear = new Date().getFullYear();
        // 本年第一天
        let currentYearFirst = new Date(currentYear, 0, 1);
        // 本年最后一天
        let currentYearLast = new Date(currentYear, 11, 31);
        // 本月第一天
        let currentMonthFirst = new Date(new Date().getFullYear(), new Date().getMonth(), 1);
        // 本月最后一天
        let currentMonthLast = new Date(new Date().getFullYear(), new Date().getMonth() + 1, 0);
        // 本周第一天
        let weekFirst = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() - new Date().getDay())
        // 本周最后一天
        let weekLast = new Date(new Date().getFullYear(), new Date().getMonth(), new Date().getDate() + (6 - new Date().getDay()))

获取星期几

var dt = new Date(year, month, date);     
var weekDay = ["星期天", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六"];
console.log("打印数值---",dt.getDay());
console.log("今天是:",weekDay[dt.getDay()]);

获取自然月自然周等等

自然月起始、结束

    getMonthBegin(year, month) {
      return new Date(year, month - 1, 1);
    },
    getMonthEnd(year, month) {
      return new Date(year, month, 0);
    },
/**
 * 获取自然月开始结束时间
 * @param {*} year 
 * @param {*} month 
 */
function getMonthBeginEnd(year, month) {
    if (~~year === 0 || ~~month === 0) {
        throw new Error('年月参数错误');
    }

    const result = {begin: 0, end: 0};
    const target = new Date();
    target.setFullYear(year);
    target.setMonth(month - 1);
    target.setDate(1);
    target.setHours(0);
    target.setMinutes(0);
    target.setSeconds(0);
    target.setMilliseconds(0);
    result.begin = target.getTime();

    const now = new Date();
    if (target.getFullYear() + target.getMonth() >= now.getFullYear() + now.getMonth()) {
        result.end = now.getTime();
        console.log(result);
        console.log(new Date(result.begin), new Date(result.end));
        return result;
    }

    target.setMonth(month);//当月的下个月1日 0时0分0秒
    target.setSeconds(-1);//前1秒,即昨天最后1秒钟,也就是上个月的最后一秒钟
    result.end = target.getTime();

    console.log(result);
    console.log(new Date(result.begin), new Date(result.end));
    return result;
}
/**
 * 获取自然日开始结束时间
 * @param {*} year 
 * @param {*} month 
 * @param {*} date 
 */
function getDateBeginEnd(year, month, date) {
    if (~~year === 0 || ~~month === 0 || ~~date === 0) {
        throw new Error('年月日参数错误');
    }

    const result = {begin: 0, end: 0};
    const target = new Date();
    target.setFullYear(year);
    target.setMonth(month - 1);
    target.setDate(date);
    target.setHours(0);
    target.setMinutes(0);
    target.setSeconds(0);
    target.setMilliseconds(0);
    result.begin = target.getTime();
    const targetDateCount = target.getFullYear() + target.getMonth() + target.getDate();

    const now = new Date();
    const nowDateCount = now.getFullYear() + now.getMonth() + now.getDate();
    if (targetDateCount >= nowDateCount) {
        result.end = now.getTime();
        console.log(0, result);
        console.log(new Date(result.begin), new Date(result.end));
        return result;
    }

    target.setDate(target.getDate() + 1);//次日0时0分0秒
    target.setSeconds(-1);//前1秒,即当日最后1秒钟
    result.end = target.getTime();

    console.log(1, result);
    console.log(new Date(result.begin), new Date(result.end));
    return result;
}

/**
 * 获取自然周开始结束时间
 * @param {*} year 
 * @param {*} month 
 * @param {*} number 第几周
 */
function getWeekByMonth(year, month, number) {
    const weekCount = getWeekCountInMonth(year, month);
    const result = {begin: 0, end: 0, list: weekCount};
    const target = new Date();
    target.setFullYear(year);
    target.setMonth(month - 1);
    target.setDate(1);
    target.setHours(0);
    target.setMinutes(0);
    target.setSeconds(0);
    target.setMilliseconds(0);
    let targetDay = target.getDay();
    targetDay = targetDay === 0 ? 7 : targetDay;

    if (number === weekCount[0]) {
        console.log(month + '月第' + number + '周起始', target);
        result.begin = target.getTime();
        target.setDate(target.getDate() + (7 - targetDay));//设置到周日最后一秒
        target.setHours(23);
        target.setMinutes(59);
        target.setSeconds(59);
        target.setMilliseconds(0);
        console.log(month + '月第' + number + '周截止', target);
        result.end = target.getTime();
        console.log(result);
        return result;
    }

    target.setDate(target.getDate() + (7 - targetDay) + 1);//对其到周一,设置到第二个周一0时0分0秒
    target.setDate(target.getDate() + 7 * (number - 2));//设置到第n周周日
    console.log(month + '月第' + number + '周起始', target);
    result.begin = target.getTime();

    if (number === weekCount[weekCount.length - 1]) {
        target.setMonth(month);//次月1日
        target.setDate(1);
        target.setHours(0);
        target.setMinutes(0);
        target.setSeconds(0);
        target.setMilliseconds(-1);//向前到当月最后1毫秒
        result.end = target.getTime();
        console.log(month + '月第' + number + '周截止', target);
        console.log(result);
        return result;
    }

    target.setDate(target.getDate() + 6);//设置到第n周周日
    target.setHours(23);
    target.setMinutes(59);
    target.setSeconds(59);
    target.setMilliseconds(0);
    result.end = target.getTime();
    console.log(month + '月第' + number + '周截止', target);
    console.log(result);
    return result;
}

/**
 * 获取每月有多少周
 * @param {*} year 
 * @param {*} month 
 */
function getWeekCountInMonth(year, month) {
    const list = [];
    const target = new Date();
    let offset = 1;
    target.setFullYear(year);
    target.setMonth(month - 1);
    target.setDate(1);
    target.setHours(0);
    target.setMinutes(0);
    target.setSeconds(0);
    target.setMilliseconds(0);
    let targetDay = target.getDay();
    targetDay = targetDay === 0 ? 7 : targetDay;

    if (targetDay !== 1) {
        console.log(targetDay);
        list.push(offset);
        offset = offset + 1;
        target.setDate(target.getDate() + (7 - targetDay) + 1);//对齐到周一
    }

    for (let i = offset; i <= 5; i++) {
        list.push(offset);
        offset = offset + 1;
        target.setDate(target.getDate() + 7);//设置到次周一0时分秒
        target.setMilliseconds(-1);//向前1毫秒到本周最后1毫秒
        console.log(target);
        if ((target.getMonth() + 1) !== month) {
            break;
        }
    }
    console.log(month + '月周数', list);
    return list;
}

/**
 * 获取上一月时间
 * @param {} date 
 */
function getPreMonth (date) {
    var _date = dateFormat('YYYY-MM', new Date(date));
    var arr = _date.split('-');
    var year = arr[0]; // 获取当前日期的年份
    var month = arr[1]; // 获取当前日期的月份
    var day = arr[2]; // 获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); // 获取当前日期中月的天数
    var year2 = year;
    var month2 = parseInt(month) - 1;
    if (month2 === 0) {
        year2 = parseInt(year2) - 1;
        month2 = 12;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }
    var t2 = year2 + '-' + month2;
    return t2;
}
/**
 * 获取下一月时间
 * @param {时间} date 
 */
function getNextMonth (date) {
    var _date = dateFormat('YYYY-MM', new Date(date));
    var arr = _date.split('-');
    var year = arr[0]; // 获取当前日期的年份
    var month = arr[1]; // 获取当前日期的月份
    var day = arr[2]; // 获取当前日期的日
    var days = new Date(year, month, 0);
    days = days.getDate(); // 获取当前日期中的月的天数
    var year2 = year;
    var month2 = parseInt(month) + 1;
    if (month2 === 13) {
        year2 = parseInt(year2) + 1;
        month2 = 1;
    }
    var day2 = day;
    var days2 = new Date(year2, month2, 0);
    days2 = days2.getDate();
    if (day2 > days2) {
        day2 = days2;
    }
    if (month2 < 10) {
        month2 = '0' + month2;
    }

    var t2 = year2 + '-' + month2;
    return t2;
}
/**
 * 格式化时间
 * @param {YYYY-MM-DD hh:mm:ss} String 
 * @param {时间} date 
 */
function dateFormat (fmt, date) {
    date = new Date(date);
    let ret;
    let opt = {
        'Y+': date.getFullYear().toString(), //
        'M+': (date.getMonth() + 1).toString(), //
        'D+': date.getDate().toString(), //
        'h+': date.getHours().toString(), //
        'm+': date.getMinutes().toString(), //
        's+': date.getSeconds().toString() //
    // 有其他格式化字符需求可以继续添加,必须转化成字符串
    };
    for (let k in opt) {
        ret = new RegExp('(' + k + ')').exec(fmt);
        if (ret) {
            fmt = fmt.replace(ret[1], (ret[1].length === 1) ? (opt[k]) : (opt[k].padStart(ret[1].length, '0')));
        }
    }
    return fmt;
}
// getMonthBeginEnd(2019, 9);
// getDateBeginEnd(2019, 10, 16);
// getWeekByMonth(2019, 10, 5);

 

前面或后面多少天

    GetPreDay(val) {
      let day = new Date(new Date().getTime() - val * 24 * 60 * 60 * 1000)
      return day
    }

 标准时间和时间戳互转

let timestamp = (new Date()).valueOf();
console.log(new Date(timestamp))

到元素位置

        // 方法1:scrollTop 滚动到某位置
        document.documentElement.scrollTop = 500
        // 方法2:scrollTo,scrollBy,scroll滚动到某位置
        // ref的元素不能是display:none,要加this.$nextTick
        this.$nextTick(() => {
          this.$refs.kkkkk.scrollTo(0, 500)
        })
        // 方法3:scrollIntoView() 实现滚动到具体某元素
        this.$nextTick(() => {
          let container = this.$el.querySelector('.echarts-wrapper')
          container.scrollIntoView()
        })

 平滑滚动

//console.log(this.$el.querySelector('.echarts-wrapper').getBoundingClientRect())
// behavior  类型String,表示滚动行为,支持参数 smooth(平滑滚动),instant(瞬间滚动),默认值auto,实测效果等同于instant
        window.scrollTo({
          top: this.$el.querySelector('.echarts-wrapper').getBoundingClientRect().top,
          behavior: 'smooth'
        })

 以流的方式下载文件

// res.data为请求到的blob
let url = window.URL.createObjectURL(res.data)
let link = document.createElement('a')
link.style.display = 'none'
link.href = url
link.setAttribute('download', filename)
document.body.appendChild(link)
link.click()

 获取图片大小

      function checkPicurl(url) {
        let img = new Image()
        img.src = url
        img.onerror = function () {
          alert(name + ' 图片加载失败,请检查url是否正确')
          return false
        }

        if (img.complete) {
          console.log(img.width + ' ' + img.height)
        } else {
          img.onload = function () {
            console.log(img.width + ' ' + img.height)
            img.onload = null//避免重复加载
          }
        }
      }
      checkPicurl('http://www.helloin.com/webpic/20160830/20160830165639_6406.jpg')

 页面切换动画

      <transition name="slide-fade">
        <router-view/>
      </transition>
  .slide-fade {
    position: absolute;
    left: 0;
    right: 0;
  }

  .slide-fade-enter-active {
    transition: all 0.5s ease;
  }

  .slide-fade-leave-active {
    transition: all .1s cubic-bezier(2.0, 0.5, 0.5, 1.0);
  }

  .slide-fade-enter, .slide-fade-leave-to {
    left: 0;
    right: 0;
    transform: translateX(50px);
    opacity: 0;
  }

 无缝滚动(上)demo list1 list2高度需要一致

      let box = document.getElementById('demo');
      let l1 = document.getElementById('list1');
      let l2 = document.getElementById('list2');
      l2.innerHTML = l1.innerHTML;

      function scrollup() {
        if (box.scrollTop >= l1.offsetHeight) {
          box.scrollTop = 0;
        } else {
          box.scrollTop++;
        }
      }
      let scrollMove = setInterval(scrollup, 80);
      box.onmouseover = function () {
        clearInterval(scrollMove)
      };
      box.onmouseout = function () {
        scrollMove = setInterval(scrollup, 80);
      }

 无缝上下滚动  左右滚动

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Title</title>
  <style>
    * {
      margin: 0;
      padding: 0;
      list-style-type: none;
    }

    a, img {
      border: 0;
    }

    body {
      font: 12px/180% Arial, Helvetica, sans-serif, "新宋体";
    }
    /* marqueeleft */
    .marqueeleft {
      height: 136px;
      width: 474px;
      overflow: hidden;
      margin: 40px auto;
    }

    .marqueeleft ul {
      float: left;
    }

    .marqueeleft li {
      float: left;
      margin: 0 5px;
      display: inline;
      width: 148px;
      height: 133px;
      overflow: hidden;
    }

    .marqueeleft li .pic {
      display: block;
      border: #ccc 1px solid;
      width: 135px;
      height: 104px;
      padding: 2px;
      overflow: hidden;
    }

    .marqueeleft li .txt {
      text-align: center;
      height: 23px;
      line-height: 23px;
    }

    /* marqueetop */
    .marqueetop {
      height: 329px;
      width: 148px;
      overflow: hidden;
      margin: 40px auto;
    }

    .marqueetop li {
      padding: 5px 0;
      width: 148px;
      height: 133px;
      overflow: hidden;
    }

    .marqueetop li .pic {
      display: block;
      border: #ccc 1px solid;
      width: 135px;
      height: 104px;
      padding: 2px;
      overflow: hidden;
    }

    .marqueetop li .txt {
      text-align: center;
      height: 23px;
      line-height: 23px;
    }
  </style>
</head>
<body>
<div id="marquee1" class="marqueeleft">
  <div style="width:8000px;">
    <ul id="marquee1_1">
      <li>
        11111111
      </li>
      <li>
        11111111
      </li>
      <li>
        11111111
      </li>
      <li>
        11111111
      </li>
    </ul>
    <ul id="marquee1_2"></ul>
  </div>
</div><!--marqueeleft end-->

<div id="marquee2" class="marqueetop">
  <div style="height:8000px;">
    <ul id="marquee2_1">
      <li>
       11111111
      </li>
      <li>
        11111111
      </li>
      <li>
        11111111
      </li>
      <li>
        11111111
      </li>
    </ul>
    <ul id="marquee2_2"></ul>
  </div>
</div><!--marqueeleft end-->
<script>
  //js无缝滚动代码
  function marquee(i, direction) {
    var obj = document.getElementById('marquee' + i);
    var obj1 = document.getElementById('marquee' + i + '_1');
    var obj2 = document.getElementById('marquee' + i + '_2');
    if (direction == 'up') {
      if (obj2.offsetTop - obj.scrollTop <= 0) {
        obj.scrollTop -= (obj1.offsetHeight + 20);
      } else {
        var tmp = obj.scrollTop;
        obj.scrollTop++;
        if (obj.scrollTop == tmp) {
          obj.scrollTop = 1;
        }
      }
    } else {
      if (obj2.offsetWidth - obj.scrollLeft <= 0) {
        obj.scrollLeft -= obj1.offsetWidth;
      } else {
        obj.scrollLeft++;
      }
    }
  }

  function marqueeStart(i, direction) {
    var obj = document.getElementById('marquee' + i);
    var obj1 = document.getElementById('marquee' + i + '_1');
    var obj2 = document.getElementById('marquee' + i + '_2');

    obj2.innerHTML = obj1.innerHTML;
    var marqueeVar = window.setInterval('marquee(' + i + ', \'' + direction + '\')', 50);
    obj.onmouseover = function () {
      window.clearInterval(marqueeVar);
    }
    obj.onmouseout = function () {
      marqueeVar = window.setInterval('marquee(' + i + ', \'' + direction + '\')', 50);
    }
  }

  marqueeStart(1, 'left');
  marqueeStart(2, 'up');
</script>
</body>
</html>

 自定点击

1.若是没有v-for循环,则直接放入directive自定义指令。

<template>
     <div class="clickdown" @click="myClick()" v-clickDown>自动点击</div>
</template>
export default {
 directives: {
            clickDown: {
                inserted(el) {
                        el.click()
                }
            }
        }
}

2.若是有v-for循环,需要自动点击索引第一个,则需要binding。

<template>
      <div class="clickdown" @click="myClick()" v-for="(item,index) in list" :key="index" v-clickDown="index">自动点击索引第一个</div>
</template>
export default {
 directives: {
            clickDown: {
                inserted(el,binding,index) {
                    if(binding.value===0){
                        el.click()
                    }
                }
            }
        }
}

 css已知盒子大小,盒子中的图片铺满但不变形

css方法

.banner
    width 100%
    height 100vw
    background-color pink
    overflow hidden

    img
        width 100%
        height 100%
        object-fit cover

js方法

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <title></title>
        <style>
            .div{width:400px;height: 400px;border:1px solid #ddd; overflow: hidden;}
            img{width: 100%;}
        </style>
    </head>
    <body>
        <div class="div" id="div">
            <img src="img/test.jpg" id="ele" />
        </div>
    </body>
    <script>
        var ele = document.getElementById("ele");
        var div = document.getElementById("div");
        ele.onload = function(){
            if(ele.naturalHeight < div.offsetHeight){
                ele.style.width = "auto";
                ele.style.height = "100%";
            }
        }
          
    </script>
</html>

使用resize时间,键盘弹起会触发该事件,此时window.innerHeight比窗口高度要小,进行按钮的隐藏即可,完美兼容ios和安卓

        // 窗口高度
        const H = window.innerHeight

        // 页面初始化后绑定resize方法
        window.addEventListener('resize', () => {
          if (window.innerHeight < H) {
            // 隐藏按钮
            this.showBtn = false
            })
          } else {
            // 显示按钮
            thisshowBtn = true
            })
          }
        })

如果想在methods中使用filters的方法,相应的就有两种方法

使用全局的filter: Vue.filters['filterName'] (val)
使用局部的filter: this.$options.filters['filterName'] (val)

调用微信扫码(先获取签名)

configWx(apiList, callback) {
      let url = location.href.split('#')[0];
      let that = this;
      getWXSign(url).then(res => {
        console.log(res.data.data);
        that.appId = res.data.data.appid;
        that.timestamp = res.data.data.timestamp;
        that.nonceStr = res.data.data.noncestr;
        that.signature = res.data.data.signature;
        // eslint-disable-next-line no-undef
        wx.config({
          debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,
          appId: that.appId, // 必填,公众号的唯一标识
          timestamp: that.timestamp, // 必填,生成签名的时间戳
          nonceStr: that.nonceStr, // 必填,生成签名的随机串
          signature: that.signature, // 必填,签名
          jsApiList: apiList // 必填,需要使用的JS接口列表
        });
        setTimeout(() => {
          callback();
        }, 500);
      });
    },
      const apiList = ['scanQRCode', 'chooseImage', 'uploadImage'];
      this.configWx(apiList, () => {
        // eslint-disable-next-line no-undef
        wx.ready(function() {
          // eslint-disable-next-line no-undef
          // wx.scanQRCode({
          //   needResult: 1, // 默认为0,扫描结果由微信处理,1则直接返回扫描结果,
          //   scanType: ['qrCode', 'barCode'], // 可以指定扫二维码还是一维码,默认二者都有
          //   success: function(res) {
          //     let result = res.resultStr; // 当needResult 为 1 时,扫码返回的结果
          //     console.log(result);
          //   },
          //   fail: function() {
          //     if (typeof fail === 'function') {
          //       console.log('调用扫码失败');
          //     }
          //   }
          // });

          // eslint-disable-next-line no-undef
          wx.chooseImage({
            count: 1, // 默认9
            sizeType: ['original', 'compressed'], // 指定是原图还是压缩图,默认都有
            sourceType: ['album', 'camera'], // 指定来源是相册还是相机,默认都有
            success: function(res) {
              let localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
              // eslint-disable-next-line no-undef
              wx.uploadImage({
                localId: localIds.toString(), // 需要上传的图片的ID,由chooseImage接口获得
                isShowProgressTips: 1, // 进度提示
                success: function(res) {
                  let serverId = res.serverId; // 返回图片的服务器端ID,即mediaId
                  //将获取到的 mediaId 传入后台 方法savePicture
                  // uploadImageFile(mediaId).then(res => {
                  //   console.log(res.data.data);
                  // });
                  // eslint-disable-next-line no-undef
                },
                fail: function(res) {
                  this.$toast('图片上传失败,请重试');
                }
              });
            }
          });
        });
      });
取消鼠标右键限制

javascript:alert(document.onselectstart = document.onbeforecopy = document.oncontextmenu = document.onmousedown = document.onkeydown = function(){return true;});void(document.body.onmouseup=''); void(document.body.onselectstart=''); void(document.body.onmouseup=''); void(document.body.oncopy='');

 按钮切换,选择取消

 <span class="btn" v-for="(item, index) in msg" :class="{ isActive: isChange === index }" @click="isChoose(index, item)">{{ item.name }}</span>
data() {
    return {
      msg: [
        { name: '项目1', id: 1 },
        { name: '项目2', id: 2 },
        { name: '项目3', id: 3 }
      ],
      isChange: -1
    };
  },

 isChoose(index, item) {
      if (index !== this.isChange) {
        this.isChange = index;
      } else {
        this.isChange = -1;
      }
    }

 不使用%来判断奇数还是偶数

function isEven(num){
  if(num&1){
    return false;
  }else{
    return true;
  }
}

// 递归
function isEven(num){
  if(num < 0 || num === 1){
    return false;
  }
  if(num == 0 ) {
    return true;
  }
  return isEven(num -2);
}

 取数据

      let table = [
        'H', 'Hydrogen', '1.00794', 1, 1,
        'He', 'Helium', '4.002602', 18, 1,
        'Li', 'Lithium', '6.941', 1, 2,
        'Be', 'Beryllium', '9.012182', 2, 2,
        'B', 'Boron', '10.811', 13, 2,
        'C', 'Carbon', '12.0107', 14, 2,
        'N', 'Nitrogen', '14.0067', 15, 2,
        'O', 'Oxygen', '15.9994', 16, 2,
        'F', 'Fluorine', '18.9984032', 17, 2,
        'Ne', 'Neon', '20.1797', 18, 2,
        'Na', 'Sodium', '22.98976...', 1, 3,
        'Mg', 'Magnesium', '24.305', 2, 3,
        'Al', 'Aluminium', '26.9815386', 13, 3,
        'Si', 'Silicon', '28.0855', 14, 3
      ];
      for (let i = 0; i < table.length; i += 5) {
        console.log(table[i])
      }

运行计时

console.time("str")  //开始
console.timeEnd("str") //结束

 任意进制转换

(13558780000).toString(36)

转换回来

parseInt('688jpls',36)

 

posted @ 2019-08-15 13:43  ronle  阅读(480)  评论(0)    收藏  举报