【微信小程序】左右滚动公告效果

本文主要讲的是无限循环左右滚动的公告

先上效果图

原理是设置公告的左移距离,不断减小,当左移距离大于公告长度(即公告已移出屏幕),重新循环。
下面将代码贴上:


CSS样式需根据自己的页面调整一下位置

.notice-wrap{background:#FF3766;padding:10rpx 70rpx 10rpx 0;height:50rpx;}
.ovh{overflow:hidden}
.font28{font-size:28rpx}
.relative{position:relative}
.notice{color:#fff;width:100%;height:40rpx;}
.marquee_text {
  white-space: nowrap;
  position: absolute;
  top: 0;
}
.close-icon{position:absolute;right:15rpx;top:114rpx;}
.icon40{width:40rpx;height:40rpx;}   
.right{float:right}
.icon{display:inline-block;width:32rpx;height:32rpx;background-size:contain;}
    //初始化数据
    hideNotice: false,
    notice: '哈哈哈哈哈哈,我是滚动的公告,快来抓我呀~',
    marqueePace: 1,//滚动速度
    marqueeDistance: 10,//初始滚动距离
    size: 12,
    interval: 20, // 时间间隔
    countTime: ''

  onLoad: function() {
   let data = {},that = this;
    var length = that.data.notice.length * that.data.size; //文字长度
    var windowWidth = wx.getSystemInfoSync().windowWidth; // 屏幕宽度
    that.setData({length,windowWidth});
    that.setData({
      marqueeDistance: windowWidth
    });
    that.run1();
  },

  run1: function () {
    var that = this;
    that.data.countTime = setInterval(function () {
      if (-that.data.marqueeDistance < that.data.length) {
        that.setData({
          marqueeDistance: that.data.marqueeDistance - that.data.marqueePace,
        });
      } else {
        clearInterval(that.data.countTime);
        that.setData({
          marqueeDistance: that.data.windowWidth
        });
        that.run1();
      }
    }, that.data.interval);
  },
})

你可能感兴趣的:(【微信小程序】左右滚动公告效果)