微信小程序实现文字从右往左无限滚动(类似公告)

林羽凡小程序

布局页面wxml

<scroll-view class="container">
  <view class="scrolltxt">
    <view class="marquee_box">
      <view class="marquee_text" style="transform: translateX(-{{marqueeDistance}}px)">
        <text>{{text}}</text>
        <text style="margin-right:{{marquee_margin}}px;"></text>
        <text style="margin-right:{{marquee_margin}}px;">{{text}}</text>        
      </view>
    </view>
  </view>
</scroll-view>

样式页面 wxss

.container {height: 100%;display: flex;flex-direction: column;justify-content: space-between;box-sizing: border-box;}
.scrolltxt{padding:0 20rpx;background:#f8f8f8;}
.marquee_box {position:relative;color:#333;height:90rpx;display:block;overflow:hidden;} 
.marquee_text {white-space: nowrap;position:absolute;top:0;font-size:14px;height:90rpx;line-height:90rpx;}

小程序 js页面

Page({
  /**
   * 页面的初始数据
   * Linyufan.com
   */
  data: {
    text: "这是一条测试公告,看看效果怎么样,2019年3月23日",
    marqueePace: 1,//滚动速度
    marqueeDistance: 0,//初始滚动距离
    marquee_margin: 30,
    size:14,
    interval: 20 // 时间间隔
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {  
  },
  onShow: function () {
    var that = this;
    var length = that.data.text.length * that.data.size;//文字长度
    var windowWidth = wx.getSystemInfoSync().windowWidth;// 屏幕宽度
    //console.log(length,windowWidth);
    that.setData({
      length: length,
      windowWidth: windowWidth
    });
    that.scrolltxt();// 第一个字消失后立即从右边出现
  },

  scrolltxt: function () {
    var that = this;
    var length = that.data.length;//滚动文字的宽度
    var windowWidth = that.data.windowWidth;//屏幕宽度
    if (length > windowWidth){
      var interval = setInterval(function () {
        var maxscrollwidth = length + that.data.marquee_margin;//滚动的最大宽度,文字宽度+间距,如果需要一行文字滚完后再显示第二行可以修改marquee_margin值等于windowWidth即可
        var crentleft = that.data.marqueeDistance;
        if (crentleft < maxscrollwidth) {//判断是否滚动到最大宽度
          that.setData({
            marqueeDistance: crentleft + that.data.marqueePace
          })
        }
        else {
          //console.log("替换");
          that.setData({
            marqueeDistance: 0 // 直接重新滚动
          });
          clearInterval(interval);
          that.scrolltxt();
        }
      }, that.data.interval);
    }
    else{
      that.setData({ marquee_margin:"1000"});//只显示一条不滚动右边间距加大,防止重复显示
    } 
  }
})

林羽凡小程序

其他演示直接浏览小程序即可。

  • 5
    点赞
  • 48
    收藏
    觉得还不错? 一键收藏
  • 12
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值