美文网首页vue
vue中实现div自由拖拽

vue中实现div自由拖拽

作者: 扶得一人醉如苏沐晨 | 来源:发表于2022-07-26 12:29 被阅读0次

 给div绑定一个自定义指令 v-drag

给div设置绝对定位

写自定义指令

//自定义指令

directives: {

        drag: {

            // 指令的定义

            bind: function(el) {

                let oDiv = el;  // 获取当前元素

                oDiv.onmousedown = (e) => {

                    console.log('onmousedown')

                    // 算出鼠标相对元素的位置

                    let disX = e.clientX - oDiv.offsetLeft;

                    let disY = e.clientY - oDiv.offsetTop;

                    document.onmousemove = (e) => {

                        // 用鼠标的位置减去鼠标相对元素的位置,得到元素的位置

                        let left = e.clientX - disX;

                        let top = e.clientY - disY;

                        oDiv.style.left = left + 'px';

                        oDiv.style.top = top + 'px';

                    };

                    document.onmouseup = (e) => {

                        document.onmousemove = null;

                        document.onmouseup = null;

                    }

                }

            }

        }

    },

相关文章

网友评论

    本文标题:vue中实现div自由拖拽

    本文链接:https://www.haomeiwen.com/subject/qjjoirtx.html