小程序实现弹幕功能-无限循环,不会重叠

  • Post author:
  • Post category:小程序


以下是支付宝小程序代码,先上效果图

在这里插入图片描述

以下是axml代码:

<view class="view">
  <block a:for="{{bulletChatData}}" a:key="id">
    <text class="item"  style="animation: first 8s linear forwards;top:{{item.top}}%;color:{{item.color}};">{{index+item.text}}</text>
  </block>
</view>

js:


const app = getApp();
var bulletChatList = [];
var id = 0;
var cycle = null;  //计时器
var topArray = [0, 15, 30, 45, 60, 75, 90, 105, 120, 135, 150];//用来做随机top值
var usedTop = [];

Page({
  data: {
    bulletChatData: [],
    messageList: ['小白提问 我应该买哪个好 投入多少 多久有成果或初步成果', '我的红包呢?幸运奖都没?我冤啊,在家待业,还得', '什么时候买才是好', '买什么基金比较好', '四月份买了一点,这两个月都在跌,陆续在补,下半年行情如何?', '什么时候买入比较好', '国债收益率下降,目前投资债基,风险大不大?', '如何选择基金。如何评估基金未来潜力', '怎样选债基']
  },
  onShow: function () {
    var _this = this;
    cycle = setInterval(function () {
      let arr = _this.data.messageList
      if (arr[id] == undefined) {
        id = 0;
        // 2.无限循环弹幕
        var obj = {};
        obj.text = arr[id];
        var num = Math.floor(Math.random() * topArray.length);
        obj.top = topArray[num];//拿到随机值 Math.ceil向上取整
        // 被使用了,从原数组删掉并添加到已使用的数组里
        usedTop.push(topArray[num]);
        topArray.splice(num, 1);
        obj.color = _this.getRandomColor();
        bulletChatList.push(obj);
        _this.setData({
          bulletChatData: bulletChatList
        })
        id++;
      } else {
        var obj = {};
        obj.text = arr[id];
        var num = Math.floor(Math.random() * topArray.length);
        obj.top = topArray[num];//拿到随机值 
        // 被使用了,从原数组删掉并添加到已使用的数组里
        usedTop.push(topArray[num]);
        topArray.splice(num, 1);
        obj.color = _this.getRandomColor();
        bulletChatList.push(obj);
        _this.setData({
          bulletChatData: bulletChatList
        })
        id++;
      }
      if (usedTop.length > 5) {
        // 从已使用的数组删掉并添加到原数组里
        topArray.push(usedTop.shift());
      }
    }, 1000)
  },
  getRandomColor() {
    let rgb = []
    for (let i = 0; i < 3; ++i) {
      let color = Math.floor(Math.random() * 256).toString(16)
      color = color.length == 1 ? '0' + color : color
      rgb.push(color)
    }
    return '#' + rgb.join('')
  },
  onHide() {
    clearInterval(cycle)
    ids = 0;
    bulletChatList = []
  },

});

acss:


.item {
    position: absolute;
    white-space: nowrap;
    /* 防止向下换行*/
    animation-timing-function: linear;
    animation-fill-mode: none;
}

.view {
    z-index: 3;
    height:20%;
    width: 100%;
    position: absolute;
}

@keyframes first {
    from {
        transform: translateX(750rpx);
    }
    to {
        transform: translateX(-1000rpx);
        display: none;
    }
}

复制代码即可运行查看效果

以上就是一个完整的小程序弹幕实现的过程,不会上下重叠左右重叠,有更好的方法,欢迎留言!

本文章纯属原创,转载请注明出处!



版权声明:本文为p_pppxxxxmmm原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。