vue3 移動端拖拽懸浮窗
阿新 • • 發佈:2022-04-21
<div class="container">
<div v-my-directive class="drag-box">
<img src="@/assets/btn_tuimen.png">
</div>
</div>
</template>
<script lang="ts" setup> const vMyDirective = { beforeMount: (el: HTMLDivElement) => { el.ontouchstart = (e: TouchEvent) => { const disX: number = e.targetTouches[0].pageX - el.offsetLeft; const disY: number = e.targetTouches[0].pageY - el.offsetTop; document.ontouchmove = (e: TouchEvent) => { let left: number = e.targetTouches[0].pageX - disX; let top: number = e.targetTouches[0].pageY - disY; if(top < 50) top = 50 if(left <0) left = 0 const containerDom: HTMLDivElement = document.querySelector(".container") as HTMLDivElement; if(top > containerDom.offsetHeight - 50) top = containerDom.offsetHeight - 50 if(left > containerDom.offsetWidth - 64) left = containerDom.offsetWidth - 64 el.style.left = left + "px"; el.style.top = top + "px"; }; document.ontouchend = () => { document.ontouchmove = null; document.ontouchend = null; }; } } }
<script lang="ts" setup> const vMyDirective = { beforeMount: (el: HTMLDivElement) => { el.ontouchstart = (e: TouchEvent) => { const disX: number = e.targetTouches[0].pageX - el.offsetLeft; const disY: number = e.targetTouches[0].pageY - el.offsetTop; document.ontouchmove = (e: TouchEvent) => { let left: number = e.targetTouches[0].pageX - disX; let top: number = e.targetTouches[0].pageY - disY; if(top < 50) top = 50 if(left <0) left = 0 const containerDom: HTMLDivElement = document.querySelector(".container") as HTMLDivElement; if(top > containerDom.offsetHeight - 50) top = containerDom.offsetHeight - 50 if(left > containerDom.offsetWidth - 64) left = containerDom.offsetWidth - 64 el.style.left = left + "px"; el.style.top = top + "px"; }; document.ontouchend = () => { document.ontouchmove = null; document.ontouchend = null; }; } } }