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