CSS
*{
margin:0px;
padding:0px;
}
html{
height: 100%;
}
body{
width: 100%;
height: 100%;
}
.box{
width: 100px;
height: 100px;
background-color: lightskyblue;
position: fixed;
top: 100px;
left:100px;
cursor: move;
}
HTML
<div class="box"> </div>
JS
let box = document.querySelector('.box')
let HTML = document.documentElement,
minL =0,
minT = 0,
maxL = HTML.clientWidth - box.offsetWidth,
maxT = HTML.clientHeight - box.offsetHeight
const down =function down(ev){
let {top,left} = this.getBoundingClientRect()
this.startT = top
this.startL = left
this.startX = ev.clientX
this.startY = ev.clientY
this.addEventListener('mousemove',move);
this.addEventListener('mouseup',up
}
const move = function move(ev){
let curL = ev.clientX-this.startX+this.startL,
curT = ev.clientY-this.startY + this.startT
curL = curL<minL ? minL:(curL>maxL?maxL:curL)
curT = curT<minT ? minT:(curT>maxT?maxT:curT)
this.style.left = `${curL}px`
this.style.top = `${curT}px`
}
const up = function up(ev){
box.removeEventListener('mousemove',move);
box.removeEventListener('mouseup',up);
}
box.addEventListener('mousedown',down);
解决鼠标焦点丢失问题
let box = document.querySelector('.box')
let HTML = document.documentElement,
minL =0,
minT = 0,
maxL = HTML.clientWidth - box.offsetWidth,
maxT = HTML.clientHeight - box.offsetHeight
const down =function down(ev){
let {top,left} = this.getBoundingClientRect()
this.startT = top
this.startL = left
this.startX = ev.clientX
this.startY = ev.clientY
this._move = move.bind(this)
this._up = up.bind(this)
window.addEventListener('mousemove',this._move);
window.addEventListener('mouseup',this._up);
}
const move = function move(ev){
let curL = ev.clientX-this.startX+this.startL,
curT = ev.clientY-this.startY + this.startT
curL = curL<minL ? minL:(curL>maxL?maxL:curL)
curT = curT<minT ? minT:(curT>maxT?maxT:curT)
this.style.left = `${curL}px`
this.style.top = `${curT}px`
}
const up = function up(ev){
window.removeEventListener('mousemove',this._move);
window.removeEventListener('mouseup',this._up);
}
box.addEventListener('mousedown',down);