瀏覽代碼

首页AI图标拖拽

zhujindu 7 月之前
父節點
當前提交
645891261b
共有 2 個文件被更改,包括 31 次插入16 次删除
  1. 28 15
      src/directive/dialog/drag.js
  2. 3 1
      src/views/home/index.vue

+ 28 - 15
src/directive/dialog/drag.js

@@ -7,14 +7,20 @@ export default {
   bind(el, binding, vnode, oldVnode) {
     const value = binding.value;
     if (value == false) return;
-    var startX = 0;
-    var startY = 0;
+    let initialTouchX = 0;
+    let initialTouchY = 0;
+    let initialLeft = 0;
+    let initialTop = 0;
+
     el.addEventListener(
       'touchstart',
-      function (e) {
+      (e) => {
         e.stopPropagation();
-        startX = e.targetTouches[0].pageX - this.offsetLeft;
-        startY = e.targetTouches[0].pageY - this.offsetTop;
+        const touch = e.touches[0];
+        initialTouchX = touch.clientX;
+        initialTouchY = touch.clientY;
+        initialLeft = e.currentTarget.offsetLeft;
+        initialTop = e.currentTarget.offsetTop;
       },
       false
     );
@@ -22,17 +28,24 @@ export default {
       'touchmove',
       function (e) {
         e.stopPropagation();
-        var leftX = e.targetTouches[0].pageX - startX;
-        var topY = e.targetTouches[0].pageY - startY;
-        var thisW = e.targetTouches[0].target.clientWidth;
-        var parentW = e.targetTouches[0].target.offsetParent.clientWidth;
-        var thisH = e.targetTouches[0].target.clientHeight;
-        var parentH = e.targetTouches[0].target.offsetParent.clientHeight;
+        const clientX = e.targetTouches[0].clientX;
+        const clientY = e.targetTouches[0].clientY;
+        // 限制拖拽范围
+        const clientWidth = document.documentElement.clientWidth;
+        const clientHeight = document.documentElement.clientHeight;
+
+        // 计算边界限制
+        const maxLeft = clientWidth - this.offsetWidth;
+        const maxTop = clientHeight - this.offsetHeight;
+        // 计算基于初始位置的移动量并应用边界限制
+        const deltaX = clientX - initialTouchX;
+        const deltaY = clientY - initialTouchY;
+        const left = initialLeft + deltaX;
+        const top = initialTop + deltaY;
 
-        console.log('leftX=' + leftX);
-        console.log('topY=' + topY);
-        this.style.left = leftX + 'px';
-        this.style.top = topY + 'px';
+        // 添加边界限制
+        this.style.left = `${Math.max(0, Math.min(left, maxLeft))}px`;
+        this.style.top = `${Math.max(0, Math.min(top, maxTop))}px`;
       },
       false
     );

+ 3 - 1
src/views/home/index.vue

@@ -194,6 +194,7 @@ export default {
 </style>
 <style lang="scss">
 .homePage {
+  position: relative;
   display: flex;
   flex-direction: column;
   .myTab {
@@ -228,11 +229,12 @@ export default {
     margin-bottom: 55px;
   }
   .floatingIcon {
-    position: fixed;
+    position: absolute;
     bottom: 85px;
     right: 14px;
     width: 40px;
     z-index: 99999;
+    height: min-content;
     .AIIcon {
       width: 100%;
       display: inline-block;