欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

vue實現(xiàn)移動端div拖動效果

 更新時間:2022年03月03日 13:36:07   作者:黑月DM  
這篇文章主要為大家詳細介紹了vue實現(xiàn)移動端div拖動效果,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下

本文實例為大家分享了vue實現(xiàn)移動端div拖動的具體代碼,供大家參考,具體內(nèi)容如下

手機上會偶爾用到拖動div的效果,雖然我自己還沒遇到,先寫一個以防萬一,需要注明的是,具體實現(xiàn)代碼是我在網(wǎng)上找的,但是那個代碼存在一些問題,我又搜集了其他資料對其修改,達到了現(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>

極其簡單的結(jié)構(gòu),畢竟只是個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加了個背景顏色

效果圖

效果呢,就是你可以在屏幕范圍內(nèi)自由拖動藍色色塊,不過超出屏幕區(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 () { // 拖動結(jié)束的操作
? ? ? 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事件有學(xué)習(xí)需求呢可以自己琢磨,要是只是要用呢,復(fù)制粘貼改一改就行了。

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論