美文网首页
vue自定义指令-(拖拽指令)

vue自定义指令-(拖拽指令)

作者: 锋享前端 | 来源:发表于2018-09-18 12:16 被阅读0次

复制粘贴可用
<!DOCTYPE html>

<html>

<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title></title>
    <style type="text/css">
        * {
            padding: 0;
            margin: 0;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="box" v-trag style="width: 100px; height: 100px; background: #00B7EE;"></div>
    </div>
</body>
<script src="https://cdn.bootcss.com/vue/2.5.17-beta.0/vue.min.js"></script>
<script type="text/javascript">
    (function() {
        Vue.directive('trag', (el, binding) => {
            el.style.position ='absolute';
            el.onmousedown = function(e) {
                var startX = e.clientX - el.offsetLeft;
                var startY = e.clientY - el.offsetTop;
                document.onmousemove = function(e) {
                    var endX = e.clientX - startX;
                    var endY = e.clientY- startY;
                    el.style.left = endX  + 'px';
                    el.style.top = endY  + 'px';
                }
                document.onmouseup = function() {
                    document.onmousemove = null;
                    document.onmouseup = null;
                }
            }
        })
        var vm = new Vue({
            el: '#app'
        })
    })()
</script>

</html>

相关文章

网友评论

      本文标题:vue自定义指令-(拖拽指令)

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