写一个可拖曳的div 发表于 2020-08-03 | 分类于 JavaScript | 阅读 次 用mouse事件写一个可拖曳的div 1<div id='app'></div> 12345678#app{ border: 1px solid red; height: 100px; width: 100px; position: absolute; top: 0; left: 0;} 1234567891011121314151617181920212223242526let dragging = falselet position = nulllet app = document.getElementById('app')app.addEventListener('mousedown', e => { dragging = true position = [e.clientX, e.clientY]})document.addEventListener('mousemove', e => { if(dragging){ const x = e.clientX const y = e.clientY const deltaX = x - position[0] const deltaY = y - position[1] const left = parseInt(app.style.left || 0) const top = parseInt(app.style.top || 0) app.style.left = left + deltaX + 'px' app.style.top = top + deltaY + 'px' position = [x, y] }})document.addEventListener('mouseup', e => { dragging = false})