美文网首页
vue实现弹窗拖拽

vue实现弹窗拖拽

作者: bryan_liu | 来源:发表于2020-04-16 10:08 被阅读0次
export default {
    directives: {
        /*自定义拖拽*/
        drag: {
            inserted: function(el, binding, vnode) {
                var odiv = el.parentNode;
                odiv.onmousedown = function(eve) {
                    eve = eve || window.event;
                    var clientX = eve.clientX;
                    var clientY = eve.clientY;
                    var odivX = odiv.offsetLeft;
                    var odivY = odiv.offsetTop;
                    var odivLeft = clientX - odivX;
                    var odivTop = clientY - odivY;
                    var clientWidth = document.documentElement.clientWidth;
                    var oWidth = odiv.clientWidth;
                    var odivRight = clientWidth - oWidth;
                    var clientHeight = document.documentElement.clientHeight;
                    var oHeight = odiv.clientHeight;
                    var odivBottom = clientHeight - oHeight;
                    document.onmousemove = function(e) {
                        e.preventDefault();
                        var left = e.clientX - odivLeft;
                        if (left < 0) {
                            left = 0
                        }
                        if (left > odivRight) {
                            left = odivRight
                        }
                        var Top = e.clientY - odivTop;
                        if (Top < 0) {
                            Top = 0
                        }
                        if (Top > odivBottom) {
                            Top = odivBottom
                        }
                        odiv.style.left = left + "px";
                        odiv.style.top = Top + "px";
                    }
                    document.onmouseup = function() {
                        document.onmouseup = "";
                        document.onmousemove = "";
                    }
                }
            }
        },
        /*阻止拖拽*/
        stopdrag: {
            inserted: function(el, binding, vnode) {
                let element = el;
                element.onmousedown = function(e) {
                    e.stopPropagation()
                }
            }
        }
    }
}

使用方法:
在需拖拽功能的元素上添加v-drag启用:


启用.png

在不需拖拽的元素上添加v-stopdrag阻止:


阻止.png

相关文章

网友评论

      本文标题:vue实现弹窗拖拽

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