js常用函数整理

138 阅读2分钟

内置构造函数

// 自定义事件
const event = new customEvent('customEvent')
window.addEventListener('customEvent', () => {)
window.dispatch(event)
// 监控元素是否可见
const observer = new IntersectionObserver((e) => {
      console.log(e[0].target, e[0].intersectionRatio) // 可见范围
    },
    {threshold: 0.5})// 阈值上报
observer.observe(document.getElementById('app'))

window对象

window.innerWidth // 获取浏览器宽度
window.innerWidth // 获取浏览器高度
window.devicePixelRatio // 物理像素与css像素比
window.requestIdleCallback(callback) //浏览器空闲时调用cb
window.onbeforeunload = function(){return "onbeforeunload is work";} // 页面离开时
window.onunhandledrejection = (e) => { console.log(e.msg, e.stash)} // promise 错误
window.performance.timing  //获取网页性能指标(毫秒级)
window.performance.getEntries()[0]  //获取网页性能指标(微秒级)

window.open('www.baidu.com', 'wroxWindow', 'width=400, height=400') //打开窗口
window.print() // 显示打印对话框

timestamp-diagram.svg

Document对象

document.getComputedStyle() // 获取元素样式

Event对象

e.clientX // 获取鼠标x坐标
e.clientY// 获取鼠标y坐标

dom对象

ele.contains(child) //是否包含子元素
ele.scrollToView() // 滚动视图到指定显示位置
ele.getBoundingClientRect().left // 获取元素x坐标(相对于视口)
ele.getBoundingClientRect().top// 获取元素y坐标
ele.offsetLeft() //就是相对position不为static的 left值
ele.offsetTop()
ele.offsetParent // 元素相对position不为static的,元素为fixed或display:none为null

时间日期(内置对象构造函数)

var b = new Date(); //获取当前时间
b.getTime() //获取时间戳
b.getFullYear() //获取年份
b.getMonth()+1; //获取月份
b.getDate() //获取天
b.getHours() //获取小时
b.getMinutes() //获取分钟
b.getSeconds() //获取秒数
b.getDay() //获取星期几
b.getMilliseconds() //获取毫秒

数字(内置对象函数)

数学函数(用Math来调用):
abs(x)    返回数的绝对值。
ceil(x)    对小数进行上舍入。
floor(x)    对数进行下舍入。
round(x)    把数四舍五入为最接近的整数。
max(x,y)    返回 x 和 y 中的最高值。
min(x,y)    返回 x 和 y 中的最低值。
pow(x,y)    返回 x 的 y 次幂。
sqrt(x)    返回数的平方根。
random()    返回 0 ~ 1 之间的随机数。

类型

// 数组
// 1、不改变原来数组
let arr =[1,2,3]
arr.concat(arr2) // => [...arr, ...arr2]
arr.join() //=> '1,2,3'
arr.indexOf(1) // => 0
arr.slice(0,1) //=>[0,1)
arr.includes() 
// 改变数组方法
push pop unshift shift
arr.splice(inidex, count, add) // 位置, 个数,添加部分

Array.form(likeArray) //类数组转化成数组