方法

el.contains(e.target);  //判断是否是子元素

let {top} = this.el.getBoundingClientRect();  //获取当前元素距离屏幕位置

insertBefore方法可以appendChild功能,insertBefore(节点,null)

while循环

let myWhile = (num) => {
    while(num){
        if(num > 10){
            return num;
        }
        num = ++num
    }
    return num;
}
myWhile(1)

 lodash节流:

import _ from 'lodash'
//降低频率用节流,防抖就是最终只触发一次
let lazyHandler = _.throttle(this.lazyLoadHandler.bind(this),500);
ele.addEventListener('scroll',lazyHandler,{
      passive:true  //passive事件监听器便不能取消事件,也不会在用户滚动页面时阻止页面呈现。
});
function myDebounce(fn,delay){
    let timeout
    return function(...args){
        clearTimeout(timeout)
        timeout = setTimeout(()=>{
            fn.apply(this.args)
        },delay)
    }
}
console.log(_.debounce)
const fn = function(event){
    console.log('移动')
}
addEventListener("resize",myDebounce(fn,2000`))

 

 while循环找父级,递归找子元素

Vue.prototype.$dispatch = function(componentsName,name){
  let parent = this.$parent;
  while(parent){
    if(componentsName == parent.$options.name){
      break;
    }else{
      parent = parent.$parent;
    }
  }
  if(parent && name){
    if(name){
      parent.$emit(name)
    }
  }
  return parent;
}

Vue.prototype.$broadcast = function(componentsName,name){
  let children = this.$children;
  let arr = []
  function find(children){
    children.forEach(child => {
      if(child.$options.name == componentsName){
        arr.push(child)
        if(name){
          child.$emit(name)
        }
      }
      if(child.$children){
        find(child.$children)
      }
    })
  }
  find(children)
  return arr
}

 

//找父级 [a,c] => [a]将c放到a的_children里
let parent = path.slice(0,-1).reduce((memo,current)=>{
  return memo._children[current]
},this.root)

 

//解决小数精度,只能两个数计算

//Math.signFiguresGlobal(0.1+0.2)   Math.signFiguresGlobal(0.3-0.1)

Math.signFiguresGlobal = function(num, rank=6) {
    if(!num) return(0);
    const sign = num / Math.abs(num);
    const number = num * sign;
    const temp = rank - 1 - Math.floor(Math.log10(number));
    let ans;
    if (temp > 0) {
        ans = parseFloat(number.toFixed(temp));
    } else if (temp < 0) {
        // ans = Math.round(number / Math.pow(10, temp)) * temp;
        const temp = Math.pow(10, temp);
        ans = Math.round(number / temp) * temp;
    } else {
        ans = Math.round(number);
    }
    return (ans * sign);
};

 

 //获取url中参数 name为某一参数名称

function getUrlParam(name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
    var r = window.location.search.substr(1).match(reg);  //匹配目标参数
    if (r != null) return unescape(r[2]); return null; //返回参数值
}

 

 //遍历对象,回调函数

let obj={a:1,b:2,c:3}
let myForEach = (obj,callBack)=>{
    Object.keys(obj).forEach(key=>{
        callBack(key,obj[key])
    })
}
myForEach(obj,(key,value)=>{
    console.log(key,value)
})

 

 

 

 

posted @ 2024-03-27 17:49  石头记1  阅读(7)  评论(0)    收藏  举报