利用flex布局,实现小程序悬浮窗可拖动,可点击
先上效果图看看
来看看代码
index.wxml
<view>
<view bindtouchmove="handleSetMoveViewPos">
<view wx-if="{{!isIos}}" class="move-view" style=" top:{{top}}px;left:{{left}}px;" bindtap="getUserProfile" catchtouchmove="handleTouchMove">
<image class="img" src="https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJLUTSZpHgwZBt5NNsfPtOgd0jCdgBcOPOQBvic8jvsND5iadkA46jbdbx1StzmOJdeHEK0TsmmRzmw/132">
</image>
</view>
<cover-view wx-if="{{isIos}}" class="move-view" style=" top:{{top}}px;left:{{left}}px;" bindtap="getUserProfile" catchtouchmove="handleTouchMove">
<cover-image class="img" src="https://thirdwx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJLUTSZpHgwZBt5NNsfPtOgd0jCdgBcOPOQBvic8jvsND5iadkA46jbdbx1StzmOJdeHEK0TsmmRzmw/132">
</cover-image>
</cover-view>
</view>
<view>
哈哈哈😃哈哈哈
</view>
</view>
index.wxss
page {
background-color: skyblue;
}
.move-view {
position: fixed ; /*相对定位*/
height:120rpx;
width:120rpx;
border-radius:50%;
color: white;
/* background-color: skyblue; */
box-shadow: inset 0 0 15px 5px #fff;
text-align: center;
}
.img {
width: 120rpx;
height: 120rpx;
border-radius: 50%;
box-shadow: inset 0 0 15px 5px #fff;
}
index.js
Page({
/**
* 页面的初始数据
*/
data: {
left: 0,
top: 0,
isIos: true // 小程序运行的环境是否是ios,默认为true
},
/**
* 生命周期函数--监听页面加载
*/
onLoad: function (options) {
wx.getSystemInfo({
success: (res) => {
if (res.platform == "android") {
// 判断小程序运行的环境
this.setData({
isIos: false
})
}
}
})
},
/**
* 安卓机和ios兼容问题
*/
handleSetMoveViewPos: function (e) {
console.log('handleSetMoveViewPos,e',this.data.isIos);
// 在ios下永远都不会走这个方案,以免引起无用的计算
if (!this.data.isIos) {
const RADIUS = 30 // 悬浮窗半径
const touchPosX = e.touches[0].clientX
const touchPosY = e.touches[0].clientY
const moveViewCenterPosX = this.data.left + RADIUS
const moveViewCenterPosY = this.data.top + RADIUS
// 确保手指在悬浮窗上才可以移动
if (Math.abs(moveViewCenterPosX - touchPosX) < RADIUS && Math.abs(moveViewCenterPosY - touchPosY) < RADIUS) {
if (touchPosX > 0 && touchPosY > 0) {
this.setData({
left: touchPosX - RADIUS,
top: touchPosY - RADIUS
})
} else {
this.setData({
left: 0, // 默认显示位置 left距离
top: 0 // 默认显示位置 top距离
})
}
}
}
},
/**
* 拖拽移动
*/
handleTouchMove: function (e) {
console.log('handleTouchMove---->',e);
const RADIUS = 30 // 悬浮窗半径
const touchPosX = e.touches[0].clientX
const touchPosY = e.touches[0].clientY
if (touchPosX > 0 && touchPosY > 0) {
this.setData({
left: touchPosX - RADIUS,
top: touchPosY - RADIUS
})
} else {
this.setData({
left: 0, //默认显示位置 left距离
top: 0 //默认显示位置 top距离
})
}
},
/**
* 实现可点击效果
*/
getUserProfile(e){
wx.getUserProfile({
desc: '用于完善会员资料',
success: (res) => {
console.log('用户信息',res);
}
})
},
})