vue自定义指令:v-drag使用 拖动拖拽


<template>
    <div class="drag">
       <div ref="element" class="content" v-drag draggable="false">
          <p>文字网页</p>
       </div>
       <div style="height:2000px;width:100%"></div>
    </div>
</template>
<script >
   export default {
        data(){
            return {
                dd:"",
                inout:""
            }
        },
        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;
                };
            }
        }
   }
</script>
<style>
.drag{
    position: relative;
}
/* position:absolute;这个还是要设的,不然拖动块定不了位置 */
.content{
    position:absolute;
    height:100px;
    width:100px;
    background-color: #67C23A;
    cursor: pointer;
}
</style>

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM