uni-app-悬浮球

文章介绍了如何在Vue中创建一个可拖动的悬浮球组件,该组件使用touch事件处理移动,根据边界条件调整位置,并在特定条件下执行预定义方法。组件包括样式定义和数据绑定,可以在不同页面中复用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 先看效果:

悬浮球

1.在components中创建drag.vue 代码如下

<template>
    <view>
        <view id="_drag_button" class="drag" :style="'left: ' + left + 'px; top:' + top + 'px;'"
            @touchstart="touchstart" @touchmove.stop.prevent="touchmove" @touchend="touchend"
            @click.stop.prevent="click" :class="{transition: isDock && !isMove }">
            <image src='../..图片路径' mode="scaleToFill"></image>
        </view>
    </view>
</template>

<script>
    export default {
        name: 'drag-button',
        props: {
            isDock: {
                type: Boolean,
                default: false
            },
            existTabBar: {
                type: Boolean,
                default: false
            },            
        },

        data() {
            return {
                config: getApp().globalData.config, //全局获取
                top: 0,
                left: 0,
                width: 0,
                height: 0,
                offsetWidth: 0,
                offsetHeight: 0,
                windowWidth: 0,
                windowHeight: 0,
                isMove: true,
                edge: 10,
                value: 0
                // imgOne: '../static/dd%20(2).png',
            }
        },
        mounted() {
            const sys = uni.getSystemInfoSync();

            this.windowWidth = sys.windowWidth;
            this.windowHeight = sys.windowHeight;

            // #ifdef APP-PLUS
            this.existTabBar && (this.windowHeight -= 50);
            // #endif
            if (sys.windowTop) {
                this.windowHeight += sys.windowTop;
            }
            const query = uni.createSelectorQuery().in(this);
            query.select('#_drag_button').boundingClientRect(data => {
                this.width = data.width;
                this.height = data.height;
                this.offsetWidth = data.width / 2;
                this.offsetHeight = data.height / 2;
                this.left = this.windowWidth - this.width - this.edge;
                this.top = this.windowHeight - this.height - this.edge - 200;
            }).exec();
        },
        methods: {
            click() {
				this.$emit('newAdd');
			},
            touchstart(e) {
                // this.$emit('btnTouchstart');
            },
            touchmove(e) {
                // 单指触摸
                if (e.touches.length !== 1) {
                    return false;
                }

                this.isMove = true;
                this.left = e.touches[0].clientX - this.offsetWidth;
                let clientY = e.touches[0].clientY - this.offsetHeight;
                // #ifdef H5
                clientY += this.height;
                // #endif
                let edgeBottom = this.windowHeight - this.height - this.edge;

                // 上下触及边界
                if (clientY < this.edge) {
                    this.top = this.edge;
                } else if (clientY > edgeBottom) {
                    this.top = edgeBottom;
                } else {
                    this.top = clientY
                }

            },
            touchend(e) {
                if (this.isDock) {
                    let edgeRigth = this.windowWidth - this.width - this.edge;

                    if (this.left < this.windowWidth / 2 - this.offsetWidth) {
                        this.left = this.edge;
                    } else {
                        this.left = edgeRigth;
                    }

                }

                this.isMove = false;
            },
        }
    }
</script>

<style lang="scss">
    .drag {
        display: flex;
        justify-content: center;
        align-items: center;
        color: $uni-text-color-inverse;
        width: 100rpx;
        height: 100rpx;
        border-radius: 50%;
        font-size: $uni-font-size-sm;
        position: fixed;
        z-index: 999999;

        &.transition {
            transition: left .3s ease, top .3s ease;
        }

        image {
            width: 100%;
            height: 100%;
        }
    }
</style>

 2.在需要悬浮球的页面引入次组件

import ball from '@/components/drag.vue';

newadd为触发悬浮球的方法 可根据业务进行编写

<ball :isDock="true" :existTabBar="true" @newAdd="newAdd"></ball>

UniApp 中实现全局悬浮球功能,可以通过以下几种方法进行开发: ### 使用 `movable-area` 和 `movable-view` 实现悬浮球 这是微信小程序原生支持的一种方式,适用于需要拖动的悬浮元素。通过将 `movable-area` 设置为全屏覆盖,并在其中放置一个可移动的 `movable-view`,可以轻松实现悬浮球效果。 ```html <template> <view> <movable-area class="movable-area"> <movable-view class="movable-view" :x="x" :y="y" direction="all" @change="onChange"> <image src="../static/suspend.png"></image> </moving-view> </movable-area> </view> </template> <script> export default { data() { return { x: 320, // 初始x坐标 y: 520 // 初始y坐标 }; }, methods: { onChange(e) { // 拖拽过程中的位置变化处理 this.x = e.detail.x; this.y = e.detail.y; } } }; </script> <style scoped> .movable-area { position: fixed; top: 0; left: 0; width: 100%; height: 100%; pointer-events: none; } .movable-view { width: 96rpx; height: 96rpx; pointer-events: auto; } </style> ``` ### 全局悬浮球实现(基于 `plus.nativeObj.View`) 如果希望在 App 端实现更复杂的全局悬浮球功能(例如后台运行时仍可见),可以使用 `plus.nativeObj.View`。该 API 提供了对原生视图的操作能力,适合用于创建全局浮动窗口[^2]。 示例代码: ```javascript let url = 'https://example.com/icon.png'; let width = '40px'; let leftPos = '10px'; let bottom = '100px'; let floatBall = new plus.nativeObj.View('floatBall', { bottom: bottom, left: leftPos, width: width, height: width, radius: width }, [{ tag: 'img', id: 'icon', src: url, position: { width: width, height: width } }]); floatBall.interceptTouchEvent(true); floatBall.addEventListener('click', () => { uni.navigateTo({ url: '/pages/chat/chat' }); }); floatBall.show(); ``` ### 自定义组件 + Vuex 实现全局状态管理 为了实现全局可用的悬浮球组件,可以结合 Vue 的自定义组件和 Vuex 进行状态管理。这样可以在多个页面中统一控制悬浮球的显示与隐藏,同时避免重复渲染问题[^4]。 - 创建悬浮球组件 `SuspendBall.vue` ```html <template> <view v-if="showBall" class="suspend-ball"> <image src="/static/ball.png" @click="handleClick"></image> </view> </template> <script> export default { props: ['showBall'], methods: { handleClick() { this.$emit('click'); } } }; </script> <style scoped> .suspend-ball { position: fixed; right: 20px; bottom: 100px; width: 60px; height: 60px; z-index: 999; } </style> ``` - 在 `main.js` 中引入 Vuex 并注册全局状态 ```javascript import store from './store'; Vue.prototype.$store = store; const app = new Vue({ store, ...App }); ``` - 在任意页面中调用 ```html <suspend-ball :show-ball="showBall" @click="navigateToChat" /> ``` ### 吸附边缘功能实现 对于释放时自动吸附到屏幕左右边缘的功能,可以通过计算当前悬浮球的位置与屏幕边界的关系来判断吸附方向。具体逻辑如下: ```javascript onChange(e) { const systemInfo = uni.getSystemInfoSync(); const screenWidth = systemInfo.windowWidth; const currentX = e.detail.x; if (currentX < screenWidth / 2) { this.x = 0; // 吸附到左侧 } else { this.x = screenWidth - 96; // 吸附到右侧 } } ``` ### 总结 - 微信小程序推荐使用 `movable-area` 和 `movable-view`。 - App 端可以使用 `plus.nativeObj.View` 来实现更灵活的悬浮球- 对于全局状态管理,建议使用 Vuex 结合自定义组件。 - 吸附边缘功能可以通过简单的数学运算实现。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值