小程序上是实现拖动悬浮图标

  • 小程序上是实现拖动图标

  • 效果

  • index.wxml



    悬浮图标

  • index.ts

    let startPoint: any;
    Page({

    /**
    * 页面的初始数据
    */
    data: {
    //按钮位置参数
    buttonTop: 0,
    buttonLeft: 0,
    windowHeight: '',
    windowWidth: '',
    },

    /**
    * 生命周期函数--监听页面加载
    */
    onLoad() {

    },
    buttonInit() {
    // 获取图标控件适配参数
    var that = this;
    wx.getSystemInfo({
    success: function (res: any) {
    // 屏幕宽度、高度
    // 高度,宽度 单位为px
    that.setData({
    windowHeight: res.windowHeight,
    windowWidth: res.windowWidth,
    buttonTop: res.windowHeight * 0.70, // 这里定义按钮的初始位置
    buttonLeft: res.windowWidth * 0.70, // 这里定义按钮的初始位置
    })

    }
    })
    },
    //以下是按钮拖动事件
    buttonStart: function (e: any) {
    startPoint = e.touches[0]//获取拖动开始点
    },
    buttonMove: function (e: any) {
    const endPoint = e.touches[e.touches.length - 1]//获取拖动结束点
    //计算在X轴上拖动的距离和在Y轴上拖动的距离
    const translateX = endPoint.clientX - startPoint.clientX
    const translateY = endPoint.clientY - startPoint.clientY
    startPoint = endPoint//重置开始位置
    let buttonTop: any = this.data.buttonTop + translateY
    let buttonLeft: any = this.data.buttonLeft + translateX
    //判断是移动否超出屏幕
    const windowWidth: any = this.data.windowWidth;
    const windowHeight: any = this.data.windowHeight;
    if (buttonLeft + 60 >= windowWidth) {
    buttonLeft = windowWidth - 60;
    }
    if (buttonLeft <= 0) {
    buttonLeft = 0;
    }
    if (buttonTop <= 0) {
    buttonTop = 0
    }
    if (buttonTop + 60 >= windowHeight) {
    buttonTop = windowHeight - 60 - 40;
    }
    this.setData({
    buttonTop: buttonTop,
    buttonLeft: buttonLeft
    })
    },
    /**
    * 生命周期函数--监听页面初次渲染完成
    */
    onReady() {

    },

    /**
    * 生命周期函数--监听页面显示
    */
    onShow() {
    this.buttonInit();
    },

    /**
    * 生命周期函数--监听页面隐藏
    */
    onHide() {

    },

    /**
    * 生命周期函数--监听页面卸载
    */
    onUnload() {

    },

    /**
    * 页面相关事件处理函数--监听用户下拉动作
    */
    onPullDownRefresh() {

    },

    /**
    * 页面上拉触底事件的处理函数
    */
    onReachBottom() {

    },

    /**
    * 用户点击右上角分享
    */
    onShareAppMessage() {

    }
    })

  • index.wxss

    .move-box {
    position: fixed;
    width: 45px;
    height: 45px;
    background-color: aquamarine;
    border-radius: 50%;
    font-size:12px;
    text-align: center;
    padding: 5px;
    box-sizing: border-box;
    color:blueviolet;
    font-weight: 600;
    }

  • index.json

    {
    "navigationBarTitleText":"拖动悬浮图标",
    "usingComponents": {}
    }

posted @ 2024-04-17 09:50  不完美的完美  阅读(194)  评论(0)    收藏  举报