常见手写

12/30/2022 面试

# 实现一个可拖拽的div

div 可拖动 => 脱离文档流 监听鼠标事件:'mousedown','mousemove','mouseup' 鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离

    move() {
      const el = document.getElementById('xxx')
      const mouseDown = (e) => {
        // 鼠标点击物体那一刻相对于物体左侧边框的距离=点击时的位置相对于浏览器最左边的距离-物体左边框相对于浏览器最左边的距离
        console.log(e.clientX, e.clientY, '起始位置', el.offsetLeft)
        const X = e.clientX - el.offsetLeft
        const Y = e.clientY - el.offsetTop
        const move = (e) => {
          el.style.left = e.clientX - X + 'px'
          el.style.top = e.clientY - Y + 'px'
          console.log(e.clientX, e.clientY, '位置改变')
        }
        document.addEventListener('mousemove', move)
        document.addEventListener('mouseup', () => {
          document.removeEventListener('mousemove', move)
        })
      }
      el.addEventListener('mousedown', mouseDown)
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 防抖

export const debounce = (fn, delay = 300) => {
  let timer
  return function() {
    const args = arguments
    timer && clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
    }, delay)
  }
}
1
2
3
4
5
6
7
8
9
10

使用:

onClick: debounce(function() {
  console.log('点击')
})
1
2
3

# 节流

export const throttle = (fn, delay = 300) => {
  let flag = true
  let timer
  return function(...args) {
    if (!flag) return
    flag = false
    clearTimeout(timer)
    timer = setTimeout(() => {
      fn.apply(this, args)
      flag = true
    }, delay)
  }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
Last Updated: 12/30/2022, 2:33:12 PM