原生小程序語法寫的小程序通知欄(公告欄)上下滾動效果實現

前面寫了一個wepy框架實現相同效果的,後面有朋友問我原生的怎麼寫,然後我就修改了下代碼,實現了一個相同效果的demo

先上圖
在這裏插入圖片描述

直接上代碼,複製下就可以直接看效果了。

wxml部分

<view>
  <view class="notification_bar">
    <image class="bar_left" src="https://ss1.bdstatic.com/70cFvXSh_Q1YnxGkpoWK1HF6hhy/it/u=1155895701,546127264&fm=26&gp=0.jpg" />
    <view class="bar_text" animation="{{animationData}}">{{content}}</view>
  </view>
</view>

wxss部分

.notification_bar {
    position: fixed;
    top: 0;
    width: 100%;
    z-index: 999;
    display: flex;
    align-items: center;
    padding: 0 30rpx;
    height: 50rpx;
    overflow: hidden;
    background: #FFE4E4;
}

.bar_left {
    width: 27rpx;
    height: 25rpx;
}

.bar_text {
    margin-left: 12rpx;
    font-size: 12px;
    color: #FF7777;
}

js部分

Page({
    data: {
        contentList: ['明明於9:23,成功查看了3次!', '紅紅於9:23,成功查看了5次!', '蘭蘭於9:23,成功查看了8次!'],
        listI: -1,
        content: '歡迎進入小程序'
    },

    onLoad: function(options) {
        setInterval(() => { this.update(this.getListInfo()) }, 3000)
    },

    update(content) {
        var that = this
        var animation = wx.createAnimation()
            // 舊消息向上平移
        animation.translateY(-30).step({
                duration: 1000,
                timingFunction: 'ease-in'
            })
            // 爲了實現下一條新內容向上平移的效果,必須把內容很快平移到下方,並且不能被用戶看見,這裏其原理類似輪播圖的思路。
            // 實現方法:動畫時間設置爲1ms,過渡效果設置爲’動畫第一幀就跳至結束狀態直到結束‘
        animation.opacity(0).translateY(30).step({
                duration: 1,
                timingFunction: 'step-start'
            })
            // 新消息向上平移的同時恢復透明
        animation.opacity(1).translateY(0).step({
            duration: 1000,
            timingFunction: 'ease-out'
        })
        that.setData({
                animationData: animation.export()
            })
            // 更新內容的延時必須大於第一步動畫時間
        setTimeout(() => {
            that.setData({
                content: content
            })
        }, 1000)
    },
    getListInfo() {
        if (this.data.listI >= this.data.contentList.length - 1) {
            this.data.listI = -1
            this.getListInfo()
        } else {
            this.data.listI++
        }
        return this.data.contentList[this.data.listI]
    }
})

個人水平有限,有問題歡迎大家留言指導,僅供學習和參考。

學海無涯!努力二字,共勉!

前面有用wepy框架寫的一個類似效果,邏輯上都是一樣的,只不過他們的語法可能有點差別,有興趣的可以去看下
https://blog.csdn.net/qq_37131884/article/details/102773161

發佈了19 篇原創文章 · 獲贊 6 · 訪問量 3644
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章