微信小程序拖拽控件組件封裝

這篇文章主要為大家詳細(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>
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容