返回

实现元素拖拽

以Vue为例:

 initDrag() {
const box = document.getElementsByClassName('fast-menu-container')[0] // 获取元素
const box_inner = document.querySelector('.fast-menu-bar')
const d_max = box_inner.offsetWidth - box.offsetWidth // 可移动最大距离

let startX // 鼠标相对与div左边,上边的偏移
box.onmousedown = (e = window.event) => {
startX = e.clientX
this.isDragging = true // 设为true表示可以移动
   }

document.onmousemove = (e = window.event) => {
if (!this.isDragging) return

const moveX = e.clientX - startX // 得到距离左边移动距离
const _mname = moveX >= 0 ? 'min' : 'max'
const _max = moveX >= 0 ? d_max : d_max * -1
const scroll = Math[_mname](moveX, _max) * -1
box.scrollLeft += scroll / 8
  }

document.onmouseup = () => {
this.isDragging = false // 设置为false不可移动
}
}
分类: 前端