div小窗的拖动

最近要做一个置顶聊天框的功能,想着要给他做成可以拖动的

一开始使用的是@mousedown+@mousemove+@mouseup来进行小窗口的拖动,但是出现拖动的时候小窗会闪烁,并且位置距离也不好把控,效果不好。然后借鉴了网上大神的帖子,使用v-drage和directives对div进行拖动

首先,在控件最外面的div中加入v-drag

然后写入directives(与methods和data()是同一级的)

   data(){

  ......

   },

 methods:{

    .......

 }

// 自定义指令 —— 拖动div
    directives: {
        drag(el) {
            let oDiv = el // 当前元素
            // let self = this // 上下文
            // 禁止选择网页上的文字
            document.onselectstart = function () {
                return false
            }
            oDiv.onmousedown = function (e) {
                // 鼠标按下,计算当前元素距离可视区的距离
                let disX = e.clientX - oDiv.offsetLeft
                let disY = e.clientY - oDiv.offsetTop
                document.onmousemove = function (e) {
                    // 通过事件委托,计算移动的距离
                    let l = e.clientX - disX
                    let t = e.clientY - disY
                    // 移动当前元素
                    oDiv.style.left = l + 'px'
                    oDiv.style.top = t + 'px'
                }
                document.onmouseup = function (e) {
                    document.onmousemove = null
                    document.onmouseup = null
                }
                // return false不加的话可能导致黏连,就是拖到一个地方时div粘在鼠标上不下来,相当于onmouseup失效
                return false
            }
        }
    },

 最后就能拖动啦,很丝滑。

最后附上大佬的ui帖子https://blog.csdn.net/seeeeeeeeeee/article/details/126139493

v-drage实现的参考https://blog.csdn.net/weixin_44692055/article/details/128289481

 

posted @ 2023-07-11 09:12  妞妞猪  阅读(44)  评论(0)    收藏  举报