这个例子咋说主要还是掌握对鼠标点击和移动的坐标要计算好,初学者还是很同意混淆其中的一些概念的
div {
height: 200px;
width: 200px;
background-color: #f00;
cursor: move;
position: absolute;
left: 20px;
top: 20px;
}
var div = document.querySelector('div')
let move = null
div.addEventListener('mousedown', function(e) {
var that = this
var x = this.clientWidth / 2
var y = this.clientHeight / 2
move = function(event) {
that.style.left = event.pageX - x + 'px'
that.style.top = event.pageY - y + 'px'
}
document.addEventListener('mousemove', move)
})
div.addEventListener('mouseup', function() {
document.removeEventListener('mousemove', move)
})
关注我 持续更新 前端知识