业务中需要实现鼠标拖拽一个按钮的功能,避免遮住页面中的内容,效果如下
最终效果
于是就封装了这样一个组件
组件封装
1.html部分
<view class="gtn-container" bindtap="gotoForm" bindtouchstart="buttonStart" catchtouchmove="buttonMove"
style="top:{{buttonTop}}px;left:{{buttonLeft}}px">
<!-- {{windowHeight}} -- {{windowWidth}} -->
<van-icon name="plus" color="#fff" size="46rpx" />
</view>
2.css
.gtn-container {
position: fixed;
/* bottom: 200rpx;
right: 60rpx; */
width: 104rpx;
height: 104rpx;
display: flex;
justify-content: center;
align-items: center;
background-color: #FFAA00;
border-radius: 50%;
z-index: 9999;
}
3.json部分
{
"component": true,
"usingComponents": {
"van-icon": "@vant/weapp/icon/index"
}
}
4.核心js
//const { getStorage, setStorage } = require('~/utils/auth')
const { checkToken } = require('~/utils/isLogin')
let startPoint = null
Component({
/**
* 组件的属性列表
*/
properties: {
},
/**
* 组件的初始数据
*/
data: {
buttonTop: 0,
buttonLeft: 0,
windowHeight: 0,
windowWidth: 0
},
pageLifetimes: {
show() {
wx.getSystemInfo({
success: (res) => {
console.log(res, 'info')
//获取到设备的宽高
let h = res.windowHeight, w = res.windowWidth
this.setData({
windowHeight: h,
windowWidth: w,
/* buttonLeft: getStorage('buttonLeft') ? getStorage('buttonLeft') : w * 0.7,
buttonTop: getStorage('buttonTop') ? getStorage('buttonTop') : h * 0.7 */
buttonLeft: w * 0.7,
buttonTop: h * 0.7
})
}
})
},
hide: function () {
// 页面被隐藏
/* setStorage('buttonLeft', this.data.buttonLeft)
setStorage('buttonTop', this.data.buttonTop) */
},
},
/**
* 组件的方法列表
*/
methods: {
gotoForm() {
checkToken(() => {
wx.navigateTo({
url: '/pages/form/index'
})
})
},
buttonStart(e) {
console.log(e, 'buttonStart')
startPoint = e.touches[0]
},
buttonMove(e) {
//计算拖动后的坐标
let endPoint = e.touches[e.touches.length - 1],
disX = endPoint.clientX - startPoint.clientX,
disY = endPoint.clientY - startPoint.clientY
startPoint = endPoint
let buttonTop = this.data.buttonTop + disY,
buttonLeft = this.data.buttonLeft + disX
//判断是否超出屏幕
if (buttonLeft + 52 >= this.data.windowWidth) {
buttonLeft = this.data.windowWidth - 52
}
if (buttonLeft <= 0) {
buttonLeft = 0
}
if (buttonTop + 52 >= this.data.windowHeight) {
buttonTop = this.data.windowHeight - 52
}
if (buttonTop <= 0) {
buttonTop = 0
}
this.setData({
buttonTop,
buttonLeft
})
// console.log(disX, disY, '999')
}
}
})
最后在页面中引入使用
{
"usingComponents": {
"zp-button": "/components/round-button/index",
},
"navigationBarTitleText": "首页"
}
<zp-button />
就可以实现在小程序页面拖拽一个按钮的功能