微信小程序文字跑马灯+拖拽效果

产品需求:
在微信小程序中产品经理需要在‘使用规则’里采用文字显示不下就跑马灯,支持拖拽。
实现思路:
先让文字动起来,动画效果要用JS可控制,接下来是追加开始-拖动-结束的方法,记得及时清除定时器。

  1. wxml:
<view class='scroll'>
    <view id='txt2' class='txt' bindtouchstart="handleTouchStart" bindtouchend="handleDragend" bindtouchmove="handleTouchMove"  style='left: {{posLeft1}}px'>{{text}}</view>
  </view>
  1. wxss:
.scroll{
  position: relative;
  width: 100%;
  height: 80rpx;
  line-height: 80rpx;
  overflow: hidden;
}
.txt{
  white-space: nowrap;
}
#txt{
  position: absolute;
  top: 0;
}

3.js:

data: {
    text: '这是一行文字水平滚动效果,在小程序中实现的123456789098765432345676543', //滚动文字
    duration: 0, //水平滚动方法一中文字滚动总时间
    pace: 1,  //滚动速度
    posLeft1: 0,  //水平滚动方法二中left值
    scrollValue: 0, // 滚动容器的初始滚动位置 
    startX: 0, // 拖拽开始时的 X 轴坐标 
}
,
 // 滚动方法
  roll: function (that, txtLength, windowWidth) {
    interval1 = setInterval(function() {
      if (-that.data.posLeft1 < txtLength) {
        that.setData({
          posLeft1: that.data.posLeft1 - that.data.pace
        })
      } else {
        that.setData({
          posLeft1: windowWidth
        })
      }
    }, 20)
  },
  // 监听拖拽触手的动作  
  handleTouchStart(e) {
    clearTimeout(interval1);
    // 记录初始拖拽位置  
    this.startX = e.touches[0].clientX;
  },
// 拖拽
  handleTouchMove(e) {
    clearInterval(interval1);
    // 计算拖拽移动的距离  
    const moveX = e.touches[0].clientX - this.startX;
    this.setData({
      posLeft1: this.data.scrollValue + moveX
    })
  },
  // 拖拽结束,继续自动滚动
  handleDragend(e) {
    let that = this;
    let windowWidth = wx.getSystemInfoSync().windowWidth; //屏幕宽度
    wx.createSelectorQuery().select('#txt').boundingClientRect(function (rect) {
      let txtLength = rect.width;//滚动文字长度
      that.roll(that, txtLength, windowWidth);
    }).exec()
  },
// 初始化
  onLoad(options) {
    let that = this;
    let windowWidth = wx.getSystemInfoSync().windowWidth; //屏幕宽度
    wx.createSelectorQuery().select('#txt').boundingClientRect(function (rect) {
      let txtLength = rect.width;//滚动文字长度
      that.roll(that, txtLength, windowWidth);
    }).exec()
  },
  onHide: function() {
    clearInterval(interval1);
  }

在网上查了一些资料没有可用的,于是在跑马灯效果上进行了一些改造做成的简版效果,以上,供参考。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容