本文實例為大家分享了vue實現(xiàn)拖拽x效果的具體代碼,供大家參考,具體內(nèi)容如下
實現(xiàn)拖拽之前,先了解幾個小常識:
這兩種獲取鼠標坐標的方法,區(qū)別在于基于的對象不同:
1.clientX : 是用來獲取鼠標點擊的位置距離 當前窗口 左邊的距離
2.clientY: 是用來獲取鼠標點擊的位置距離 當前窗口 上邊的距離
3.offsetWidth: 用來獲取當前拖拽元素 自身的寬度
4.offsetHeight:用來獲取當前拖拽元素 自身的高度
5.document.documentElement.clientHeight :屏幕的可視高度
6.document.documentElement.clientWidth:屏幕的可視高度
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>vue實現(xiàn)拖拽</title> <script src="./js/vue.min.js"></script> </head> <style> *{margin: 0;padding:0;} #app{ position: relative; /*定位*/ top: 10px; left: 10px; width: 80px; height: 80px; background: #666; /*設置一下背景*/ } </style> <body> <div id="app" @mousedown="move"> {{positionX}} {{positionY}} </div> </body> <script> var vm = new Vue({ el: "#app", data: { positionX: 0, positionY: 0 }, methods: { move(e){ let odiv = e.target;// 獲取目標元素 //計算出鼠標相對點擊元素的位置,e.clientX獲取的是鼠標的位置,OffsetLeft是元素相對于外層元素的位置 let x = e.clientX - odiv.offsetLeft; let y = e.clientY - odiv.offsetTop; console.log(odiv.offsetLeft,odiv.offsetTop) document.onmousemove = (e) => { // 獲取拖拽元素的位置 let left = e.clientX - x; let top = e.clientY - y; this.positionX = left; this.positionY = top; //console.log(document.documentElement.clientHeight,odiv.offsetHeight) // 把拖拽元素 放到 當前的位置 if (left <= 0) { left = 0; } else if (left >= document.documentElement.clientWidth - odiv.offsetWidth){ //document.documentElement.clientWidth 屏幕的可視寬度 left = document.documentElement.clientWidth - odiv.offsetWidth; } if (top <= 0) { top = 0; } else if (top >= document.documentElement.clientHeight - odiv.offsetHeight){ // document.documentElement.clientHeight 屏幕的可視高度 top = document.documentElement.clientHeight - odiv.offsetHeight } odiv.style.left = left + "px"; odiv.style.top = top + "px" } // 為了防止 火狐瀏覽器 拖拽陰影問題 document.onmouseup = (e) => { document.onmousemove = null; document.onmouseup = null } } } }) </script> </html>
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com