vue實現(xiàn)移動端div拖動效果
本文實例為大家分享了vue實現(xiàn)移動端div拖動的具體代碼,供大家參考,具體內容如下
手機上會偶爾用到拖動div的效果,雖然我自己還沒遇到,先寫一個以防萬一,需要注明的是,具體實現(xiàn)代碼是我在網上找的,但是那個代碼存在一些問題,我又搜集了其他資料對其修改,達到了現(xiàn)在的樣子,所以還是要感謝寫這段代碼的大神與萬能的搜索引擎
1、分享代碼
html代碼
<template>
? <div class="main">
? ? <div ref="move_div" @touchstart="down" @touchmove="move" @touchend="end" :style="{top: top ?+ 'px', left: left ?+ 'px'}" class="drag_area"></div>
? </div>
</template>極其簡單的結構,畢竟只是個DEMO
SCSS代碼
.main{
? ? background-color: brown;
? ? height: -webkit-fill-available;
? ? .drag_area{
? ? ? width: 10vw;
? ? ? height: 10vw;
? ? ? background-color: dodgerblue;
? ? ? position: absolute;
? ? ? top: 0;
? ? ? left: 0;
? ? }
? }為了截圖顯眼,特地給main加了個背景顏色
效果圖

效果呢,就是你可以在屏幕范圍內自由拖動藍色色塊,不過超出屏幕區(qū)域我特意做了限制,不需要限制的可以自己改
JS代碼
export default {
? name: 'drag',
? data () {
? ? return {
? ? ? flags: false,
? ? ? position: {x: 0, y: 0, left: 0, top: 0},
? ? ? top: 0,
? ? ? left: 0,
? ? ? width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
? ? ? height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight
? ? }
? },
? methods: {
? ? down () { // 拖動開始的操作
? ? ? this.flags = true
? ? ? const refs = this.$refs.move_div.getBoundingClientRect()
? ? ? let touch = event
? ? ? if (event.touches) {
? ? ? ? touch = event.touches[0]
? ? ? }
? ? ? this.position.x = touch.clientX
? ? ? this.position.y = touch.clientY
? ? ? this.position.left = refs.left
? ? ? this.position.top = refs.top
? ? },
? ? move () { // 拖動中的操作
? ? ? if (this.flags) {
? ? ? ? let touch = event
? ? ? ? if (event.touches) {
? ? ? ? ? touch = event.touches[0]
? ? ? ? }
? ? ? ? const xPum = this.position.left + touch.clientX - this.position.x
? ? ? ? const yPum = this.position.top + touch.clientY - this.position.y
? ? ? ? this.left = xPum
? ? ? ? this.top = yPum
? ? ? ? this.banOut()
? ? ? ? // 阻止頁面的滑動默認事件
? ? ? ? document.addEventListener('touchmove', function () {
? ? ? ? ? event.preventDefault()
? ? ? ? }, {passive: false})
? ? ? }
? ? },
? ? end () { // 拖動結束的操作
? ? ? this.flags = false
? ? ? this.banOut()
? ? },
? ? banOut () { // 避免拖動出界的限制
? ? ? const refs = this.$refs.move_div.getBoundingClientRect()
? ? ? if (this.left < 0) {
? ? ? ? this.left = 0
? ? ? } else if (this.left > this.width - refs.width) {
? ? ? ? this.left = this.width - refs.width
? ? ? }
? ? ? if (this.top < 0) {
? ? ? ? this.top = 0
? ? ? } else if (this.top > this.height - refs.height) {
? ? ? ? this.top = this.height - refs.height
? ? ? }
? ? }
? }
}代碼呢,簡潔明了,你要是對touch事件有學習需求呢可以自己琢磨,要是只是要用呢,復制粘貼改一改就行了。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
vue-cli4創(chuàng)建項目導入Element-UI踩過的坑及解決
這篇文章主要介紹了vue-cli4創(chuàng)建項目導入Element-UI踩過的坑及解決,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-04-04
Vue3使用 createApp 自定義通用Dialog的方法
這篇文章主要介紹了Vue3使用 createApp 自定義通用Dialog的方法,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友參考下吧2024-01-01

