關於uniapp的拖動懸浮球


這兩天在做一個項目,有個小模塊是懸浮球功能,可以拖動的那種

組件也找了,發現組件那個會很卡,而且頁面會跟着滾動,球球初始位置也讓人很難受

尤其是當我一刷新球球丟了就很蒙,看來那個還是需要完善的

然后我去百度搜了搜,然后找到了解決方法,我判斷了下球球初始情況

初始是按百分比定位的,這樣對一些大屏設備還是比較友好的,

而且我還精簡了下代碼

完整的可拖動懸浮球功能如下(可復制直接使用):

注:如果球球是圖片的話,只需要把ball的那個view改成image即可

<template>
    <view>
        <view class="holdon">
            <view class="ball"
                :style="'left:'+(moveX == 0 & x>0? x+'%':moveX+'px')+';top:'+(moveY == 0 & y>0? y+'%':moveY+'px')"
                @touchstart="drag_start" @touchmove.prevent="drag_hmove" mode="aspectFit">
            </view>
        </view>
    </view>
</template>
<script>
    export default {
        //懸浮球絕對位置百分比,頁面刷新會回到這個位置
        props: {
            x: {
                type: Number,
                default: 80
            },
            y: {
                type: Number,
                default: 50
            },
            image: {
                type: String,
                default: ''
            }
        },
        data() {
            return {
                start: [0, 0],
                moveY: 0,
                moveX: 0,
                windowWidth: '',
                windowHeight: '',
            }
        },
        onShow() {
            //獲取系統分辨率
            const {
                windowWidth,
                windowHeight
            } = uni.getSystemInfoSync();
            this.windowWidth = windowWidth
            this.windowHeight = windowHeight
        },
        methods: {
            drag_start(event) {
                this.start[0] = event.touches[0].clientX - event.target.offsetLeft;
                this.start[1] = event.touches[0].clientY - event.target.offsetTop;
            },
            //判斷防止懸浮球被拖出頁面
            drag_hmove(event) {
                let tag = event.touches;
                if (tag[0].clientX < 0) {
                    tag[0].clientX = 0
                }
                if (tag[0].clientY < 0) {
                    tag[0].clientY = 0
                }
                if (tag[0].clientX > this.windowWidth) {
                    tag[0].clientX = this.windowWidth
                }
                if (tag[0].clientY > this.windowHeight) {
                    tag[0].clientY = this.windowHeight
                }
                this.moveX = tag[0].clientX - this.start[0];
                this.moveY = tag[0].clientY - this.start[1];
            },
        }
    }
</script>

<style>
    .ball {
        width: 100rpx;
        height: 100rpx;
        background: linear-gradient(to bottom, #F8F8FF, #87CEFA);
        border-radius: 50%;
        /* 防止頁面滾動條或其他事件跟着動 */
        position: fixed !important;
        z-index: 9999;
    }
</style>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM