微信小程序实现滚动字幕(小喇叭通知)

需要实现的效果:



dom部分:

<view class="notice">
  <image src="../../static/horn.png" mode="widthFix"></image>
  <view class="notice_desc">
    <view style="transform: translateX(-{{ distance }}px);">
      <text style="margin-right:{{ space }}px;"></text>
      <text id="mjltest">{{ text }}</text>
      <text style="margin-right:{{ space }}px;"></text>
      <text>{{ text }}</text>
    </view>
  </view>
</view>

css部分:

.notice {
    width: 92%;
    height: 56rpx;
    line-height: 56rpx;
    background-color: #fff;
    box-shadow: 0 3rpx 6rpx 1rpx rgba(0,97,6,0.4100);
    border-radius: 30rpx;
    position: absolute;
    top: 730rpx;
    left: 30rpx;
    display: flex;
}

.notice image {
    width: 36%;
    margin: 10rpx 18rpx;
}

.notice .notice_desc {
    margin-right: 40rpx;
    font-size: 28rpx;
    color: #333;
    overflow: hidden;
    white-space: nowrap;
}

js部分:

Page({
  data: {
    text: "需要滚动的字幕",
    step: 1, // 滚动速度
    distance: 360, // 初始滚动距离
    space: 300,
    interval: 20 // 时间间隔
  },
  onShow: function() {
    var that = this;
    var query = wx.createSelectorQuery();
    // 选择id
    query.select('#mjltest').boundingClientRect();
    query.exec(function(res) {
      var length = res[0].width;
      var windowWidth = wx.getSystemInfoSync().windowWidth; // 屏幕宽度
      that.setData({
        length: length,
        windowWidth: windowWidth,
        space:windowWidth
      });
      that.scrollling(); // 第一个字消失后立即从右边出现
    });
  },
  scrollling: function() {
    var that = this;
    var length = that.data.length; // 滚动文字的宽度
    var windowWidth = that.data.windowWidth; // 屏幕宽度
    var interval = setInterval(function() {
      var maxscrollwidth = length + that.data.space;
      var left = that.data.distance;
      if (left < maxscrollwidth) { // 判断是否滚动到最大宽度
        that.setData({
          distance: left + that.data.step
        })
      } else {
        that.setData({
          distance: 0 // 直接重新滚动
        });
        clearInterval(interval);
        that.scrollling();
      }
    }, that.data.interval);
  }
})
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容