uniapp实现全局悬浮框(按钮,页面,图片自行设置) 可拖动
话不多说直接上干货
1,在components新建组件(省去了每个页面都要引用组件的麻烦)
2,实现代码
<template>
<view class="call-plate" :style="'top:' + top + 'px;left:' + left + 'px;'" @touchmove="touchmove" @touchend="touchend" @touchstart="touchstart" v-if="popupShow">
通话中悬浮框
</view>
</template>
<script>
export default {
name: "call-screen",
emits: ["hide", "confirm"],
props: {
/**
* 默认号码
*/
number: {
type: String,
default: ""
}
},
data() {
return {
popupShow: true, // 是否显示当前页面
top: 0,
left: 0,
startTop: 0,
startLeft: 0,
startClientTop: 0,
startClientLeft: 0,
}
},
watch: {
},
computed: {
i18n() {
return this.$t
}
},
created() {
this.top = getApp().globalData.callShowTop // 获取全局存储的位置,也可以使用本地缓存存储
this.left = getApp().globalData.callShowLeft
let that = this
// 全局通知 具体字符串自行设置即可
uni.$on(this.global.CALL_SHOW_UPDATE, res => { // 更新每个页面悬浮框位置
that.top = getApp().globalData.callShowTop
that.left = getApp().globalData.callShowLeft
})
uni.$on(this.global.CALL_SHOW_OPEN, res => { // 打开每个页面悬浮框
that.popupShow = true
})
uni.$on(this.global.CALL_SHOW_CLOSE, res => { // 关闭每个页面悬浮框
that.popupShow = false
})
},
onShow() {
},
mounted() {
},
methods: {
touchmove(e) {
// 单指触摸
if (e.touches.length !== 1) {
return false;
}
this.top = e.changedTouches[0].clientY - this.startClientTop + this.startTop
this.left = e.changedTouches[0].clientX - this.startClientLeft + this.startLeft
},
touchend(e) {
getApp().globalData.callShowTop = this.top
getApp().globalData.callShowLeft = this.left
uni.$emit(this.global.CALL_SHOW_UPDATE) // 更新每个页面悬浮框位置
},
touchstart(e){
this.startTop = this.top
this.startLeft = this.left
this.startClientTop = e.changedTouches[0].clientY
this.startClientLeft = e.changedTouches[0].clientX
}
}
}
</script>
<style lang="scss" scoped>
.call-plate {
display: flex;
position: absolute;
width: 90px;
height: 160px;
z-index: 9999999;
background-color: yellow;
}
</style>
在 App.vue中全局存储悬浮框位置信息
globalData: {
callShowTop: 100, // 悬浮框top
callShowLeft: 100, // 悬浮框left
},
3,在每个需要用到悬浮框的页面引入
<template>
<view class="content">
<!--组件引用-->
<call-screen></call-screen>
</view>
</template>
发通知控制显示隐藏悬浮框
uni.$emit(that.global.CALL_SHOW_CLOSE)
uni.$emit(that.global.CALL_SHOW_OPEN)
4,实现效果
每个页面切换后都会更新最新位置