必须使用的三个事件:
1.onmousedown:鼠标按下事件
2.onmousemove:鼠标移动事件
3.onmouseup:鼠标抬起事件
<script > class Drag{ constructor(id){ this.oDiv =document.querySelector(id); this.disX=0; this.disY = 0; this.init(); } init(){ this.oDiv.onmousedown = function(e){ this.disX = e.clientX - this.oDiv.offsetLeft; this.disY = e.clientY - this.oDiv.offsetTop; document.onmousemove =this.fnmove.bind(this); document.onmouseup =this.fnup.bind(this); return false }.bind(this); } fnmove(e){ this.oDiv.style.left = e.clientX - this.disX; this.oDiv.style.top = e.clientY - this.disY; } fnup(e){ document.onmouseup = null; document.onmousemove = null ; } } new Drag('#div1') //有范围限制的拖拽 class Limited extends Drag { fnmove(e)}{ super.fnmove(e); if(this.oDiv.offsetLeft<0){ this.oDiv.style.left = 0; }else(this.oDiv.offsetLeft>> window.innerWidth - drag.offsetWidth){ this.oDiv.style.left = window.innerWidth - drag.offsetWidth; } if(this.oDiv.offsetTop <0){ this.oDiv.style.top =0 ; }else if (his.oDiv.offsetTop>window.innerHeight - drag.offsetHeight){ this.oDiv.style.top = window.innerHeight - drag.offsetHeight } } } new Limited('#div2') </script>
ps:
1.offsetLeft 和left的区别:
offsetLeft 获取的是相对于父对象的左边距; left 获取或设置相对于 具有定位属性(position定义为relative)的父对象 的左边距
如果父div的position定义为relative,子div的position定义为absolute,那么子div的style.left的值是相对于父div的值,这同offsetLeft是相同的
区别在于:
1. style.left 返回的是字符串,如28px,offsetLeft返回的是数值28,如果需要对取得的值进行计算,
还用offsetLeft比较方便。
2. style.left是读写的,offsetLeft是只读的,所以要改变div的位置,只能修改style.left。
3. style.left的值需要事先定义,否则取到的值为空。而且必须要定义在html里,我做过试验,如果定义在
css里,style.left的值仍然 为空,这就是我刚开始碰到的问题,总是取不到style.left的值。
offsetLeft则仍然能够取到,无需事先定义div的位置。
2.window.innerWidth获取窗口宽度,,offsetWidth获取盒子大小