Realize the effect of text marquee in the applet

One of the functional requirements in my applet requirements is to scroll and play when the title exceeds the specified maximum width of the title

Then there is information on the Internet, which is actually a text marquee effect, which is realized by a circular timer. In H5, <marquee></marquee>it can be implemented with a single tag, but the applet has to implement it by itself

styles in wxml

    <view class='marquee' style='width:{{marqueeWidth}}rpx;'>
        <view class='marqueeTitle' style="margin-left:{{marqueeMargin}}px;{{orientation}}:{{marqueeDistance}}px;font-size: {{size}}rpx;">{{title}}</view>
    </view>

In the registration page, define the required data and implement the JS animation

Page({
  data: {
      // 滚动标题的字段
      title: "可怜的如胸口额us客人提供是列入他一会熟练度投入好就没事电视台",
      marqueePace: 1,   //滚动速度
      orientation: 'left',  //滚动方向
      marqueeDistance: 0,   //初始滚动距离
      marqueeDistance2: 0,
      size: 28,
      marqueeWidth: 400,
      marqueeMargin: 40,
      interval: 20,
  },
  onShow: function () {
      console.log('index.onShow');
      // 标题的显示
      var that = this;
      var length = that.data.title.length * that.data.size;     //计算文字的长度
      that.setData({
          length: length,
          // 当文字长度小于屏幕长度时,需要增加补白
          marqueeMargin: length < that.data.marqueeWidth ? (that.data.marqueeWidth - length)/4 : that.data.marqueeMargin
      })
      if(that.data.length > that.data.marqueeWidth){
          that.run1();
      }
  },
  // 标题超过限制宽度时做滚动播放
  run1 : function(){
        var that = this;
        var interval = setInterval(function(){
            if(-that.data.marqueeDistance < that.data.length){
                that.setData({
                    marqueeDistance: that.data.marqueeDistance - that.data.marqueePace,
                })
            }else{
                clearInterval(interval);
                that.setData({
                    marqueeDistance : that.data.marqueeWidth
                });
                that.run1();
            }
        },that.data.interval)
  }
})

The renderings are temporarily inconvenient to send, but the code can be copied and pasted directly. There are also texts that I typed a few times first, and it may not look very elegant. . .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324647277&siteId=291194637