美文网首页【微信小程序】
【微信小程序】左右滚动公告效果

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

作者: RealHumans | 来源:发表于2019-03-30 17:28 被阅读233次

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

    先上效果图

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

    <view class='notice-wrap' hidden='{{hideNotice}}'>
      <view class='notice ovh font28 relative'>
        <view class="marquee_text" style="left:{{marqueeDistance}}px;">
          {{notice}}
        </view>
      </view>
      <image bindtap='switchNotice' src='../../imgs/close-white.png' class='close-icon icon40 right icon'></image>
    </view>
    

    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, // 时间间隔
    
      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;
        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.windowWidth
            });
            that.run1();
          }
        }, that.data.interval);
      },
    

    相关文章

      网友评论

        本文标题:【微信小程序】左右滚动公告效果

        本文链接:https://www.haomeiwen.com/subject/uhofmqtx.html