var obj = document.getElementsByClassName('qiu')[0];
obj.addEventListener('mousedown',function(event){
//获取浏览器窗口宽度 和 高度
let clientW = window.innerWidth;
let clientH = window.innerHeight;
//获取当前元素的宽高
let elW = obj.offsetWidth;
let elH = obj.offsetHeight;
//算出鼠标相对元素的位置
let pointX = event.clientX - obj.offsetLeft;//鼠标位置X减去元素距离左边距离(鼠标到元素左边的距离)
let pointY = event.clientY - obj.offsetTop;//鼠标位置Y减去距离顶部距离(鼠标到元素顶部的高度)
document.onmousemove = (e)=>{
//用鼠标的位置减去鼠标相对元素的位置,得到元素的位置
let left = e.clientX - pointX;
let top = e.clientY - pointY;
left = left<0 ? 0 : left;
top = top<0 ? 0 : top;
left = left > (clientW - elW) ? (clientW - elW) :left
top = top > (clientH - elH) ? (clientH - elH) :top
//移动当前元素
obj.style.left = left + 'px';
obj.style.top = top + 'px';
};
document.onmouseup = (e) => {
document.onmousemove = null;
document.onmouseup = null;
};
})
让小球在浏览器可视区域内拖拽自如
最新推荐文章于 2023-11-29 20:17:28 发布