### [怎样使用Vue操作DIV](https://www.prosaas.cn/article/17518) **Published:** 2018-06-04T07:13:47 **Author:** 5201314 **Excerpt:** 这次给大家带来怎样使用Vue操作DIV,使用Vue操作DIV的注意事项有哪些,下面就是实战案例,一起来看一下。… 这次给大家带来怎样使用Vue操作DIV,使用Vue操作DIV的注意事项有哪些,下面就是实战案例,一起来看一下。 效果图  demo1.gif **分清clientY pageY screenY layerY offsetY的区别** 在我们想要做出拖拽这个效果的时候,我们需要分清这几个属性的区别,这几个属性都是计算鼠标点击的偏移值,我们需要对其进行了解才可以继续实现我们的拖拽效果 clientY 指的是距离可视页面左上角的距离 pageY 指的是距离可视页面左上角的距离(不受页面滚动影响) screenY 指的是距离屏幕左上角的距离 layerY 指的是找到它或它父级元素中最近具有定位的左上角距离 offsetY 指的是距离它自己左上角的距离 一张图带大家简单了解了解  **区别** 在我们简单了解完这些个属性以后,有几个属性需要分清。 | 相同点 | 不同点 | | | --- | --- | --- | | clientY | 距离页面左上角距离 | 受页面滚动的影响 | | pageY | 距离页面左上角的距离 | 不受页面滚动影响 | | | 相同点 | 不同点 | | --- | --- | --- | | layerY | 距离元素的左上角距离 | 受元素的定位的影响,会从本元素往上找到第一个定位的元素的左上角 | | offsetY | 距离元素左上角的距离 | 计算相对于本元素的左上角,不在乎定位问题,计算的是内交点。是IE浏览器的特有属性 |  layerY与offsetY区别 **实现拖拽功能** 我们既然熟悉了这几个偏移属性的意思,那么我们就进入我们的重点。话不多说直接上代码 // darg.html
{{positionX}} {{positionY}}
//main.js let app = new Vue({ el:'#app', data:{ positionX:0, positionY:0, }, methods:{ move(e){ let op = e.target; //获取目标元素 //算出鼠标相对元素的位置 let disX = e.clientX - op.offsetLeft; let disY = e.clientY - op.offsetTop; document.onmousemove = (e)=>{ //鼠标按下并移动的事件 //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置 let left = e.clientX - disX; let top = e.clientY - disY; //绑定元素位置到positionX和positionY上面 this.positionX = top; this.positionY = left; //移动当前元素 op.style.left = left + 'px'; op.style.top = top + 'px'; }; document.onmouseup = (e) => { document.onmousemove = null; document.onmouseup = null; }; } }, computed:{}, }); 当然,我们可以将它绑定为一个自定义指令,这样的话就可以用调用指令的形式来实现拖拽效果,下面是定义自定义指令的代码 // darg.html//main.js let app = new Vue({ el:'#app', data:{}, methods:{}, directives: { drag: { // 指令的定义 bind: function (el) { let op = el; //获取当前元素 op.onmousedown = (e) => { //算出鼠标相对元素的位置 let disX = e.clientX - op.offsetLeft; let disY = e.clientY - op.offsetTop; document.onmousemove = (e)=>{ //用鼠标的位置减去鼠标相对元素的位置,得到元素的位置 let left = e.clientX - disX; let top = e.clientY - disY; //绑定元素位置到positionX和positionY上面 this.positionX = top; this.positionY = left; //移动当前元素 op.style.left = left + 'px'; op.style.top = top + 'px'; }; document.onmouseup = (e) => { document.onmousemove = null; document.onmouseup = null; }; }; } } } }); 相信看了本文案例你已经掌握了方法,更多精彩请关注知企PROSAAS其它相关文章! 推荐阅读: utils.js使用案例详解 Nuxt.js SSR的权限验证使用 以上就是怎样使用Vue操作DIV的详细内容,更多请关注知企PROSAAS其它相关文章! **Categories:** 后端开发 ---