实用原生方法汇总

150 阅读1分钟

如何获取查询参数

可以通过 DOM 自带的 URLSearchParams 来获取查询参数,也就是 URL 地址中 ? 后面的参

例如:http://localhost:3000/home/result?q=2.0
 const q= new URLSearchParams(window.location.search).get('q')
 console.log(q) // q的值为'2.0'

日期本地化处理格式

参考:dayjs 本地换化格式

使用 dayjs 的本地化格式,可以展示:2021年10年24日 格式的日期

import dayjs from 'dayjs'
// 导入本地化格式插件
import localizedFormat from 'dayjs/plugin/localizedFormat'
dayjs.extend(localizedFormat)
​
// '2021-10-24 10:24:00' => '2021年10月24日'
dayjs(detail.pubdate).locale('zh-cn').format('LL')

获取元素相关信息

dom.getBoundingClientRect() 用来获取元素相关信息,比如,元素自身大小、元素位置等

// top 元素相对于页面顶部的距离
// height 元素自身高度
const { top, height } = dom.getBoundingClientRect()

节流函数

导入 lodash 的节流函数 throttle

防抖函数

lodash 的 debounce 函数

element.scrollTo()

参考:MDN scrollTo()

element.scrollTo()
​
// 作用:使界面滚动到给定元素的指定坐标位置// 语法一:
// 第一个参数:表示水平坐标 x
// 第二个参数:表示垂直坐标 y
element.scrollTo(x, y)
​
// 语法二:
element.scrollTo({
  // x
  left: 0,
  // y
  top: 0,
  // 行为,smooth 表示有动画效果; auto 表示没有动画效果
  behavior: 'smooth'
})