這篇文章主要為大家詳細(xì)介紹了微信小程序?qū)崿F(xiàn)在界面之上可以拖拽移動控件組件,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
效果展示

按住拖動.jpg
主要代碼
在小程序目錄components文件下新建Component文件:move-btn/index

新建.png
wxml
<view class='move_btn' catchtouchmove="moveBtn" style="top:{{top}}rpx;left:{{left}}rpx">{{text}}</view>
js
properties: {
text: String //傳入組件的按鈕文字
},
data: {
top: 800, // 距離頂部的默認(rèn)位置
left: 630 // 距離左邊的默認(rèn)位置
},
methods: {
//組件實(shí)現(xiàn)拖動效果
moveBtn: function (e) {
var that = this
if (e.touches[0].clientX < (wx.getSystemInfoSync().windowWidth - 55) && e.touches[0].clientX > 0 && e.touches[0].clientY < (wx.getSystemInfoSync().windowHeight - 55) && e.touches[0].clientY > 0) {
wx.getSystemInfo({
success: function (res) {
let X = (e.touches[0].clientX * (750 / res.windowWidth));
// 將高度乘以換算后的該設(shè)備的rpx與px的比例
let Y = (e.touches[0].clientY * (750 / res.windowWidth));
// 將高度乘以換算后的該設(shè)備的rpx與px的比例
that.setData({
left: X,
top: Y
})
}
})
}
}
}
})
wxss
可以根據(jù)界面風(fēng)格自己調(diào)整樣式
.move_btn {
position: fixed;
z-index: 9;
width: 110rpx;
height: 110rpx;
box-sizing: border-box;
padding: 0 28rpx;
font-size: 24rpx;
box-sizing: border-box;
border-radius: 50%;
background: #233cff;
box-shadow: 0 0 10rpx rgba(0, 0, 0, 0.2);
color: #fff;
text-align: center;
display: flex;
justify-content: center;
align-items: center;
}
使用方法
在需要使用的界面json文件中引入
"usingComponents": {
"move-btn": "/components/move-btn/index"
}
html上添加如下代碼,傳入按鈕文字,自定義方法
<!-- 添加設(shè)備 -->
<move-btn catchtap="myMethod" text="按住拖動"></move-btn>