废话不多说代码如下
我的查看代码
let oDiv = document.querySelector('div')
let flag = false;
oDiv.addEventListener('mousedown',(e)=>{
let x = e.offsetX;
let y = e.offsetY;
flag = true;
document.addEventListener('mousemove',(event)=>{
let _w = window.innerWidth - oDiv.offsetWidth;
let _h = window.innerHeight - oDiv.offsetHeight;
let div_left = event.clientX - x;
let div_top = event.clientY - y;
div_top = Math.min(Math.max(0,div_top),_h);
div_left = Math.min(Math.max(0,div_left),_w);
if(flag){
oDiv.style.left = div_left + 'px';
oDiv.style.top = div_top + 'px';
}
})
})
oDiv.addEventListener('mouseup',()=>{
flag = false;
})