微信小程式實現走馬燈效果例項
前言
日常開發中,我們經常會遇到文字橫向迴圈滾動的效果,俗稱走馬燈,也是專案中經常會使用的一個功能。在網頁web前端很常見,今天就介紹下小程式的實現方式,一種是用的css樣式實現,另一種是運用小程式的動畫功能實現。
@keyframes 實現
利用@keyframes的規則來實現,非常方便,只需要css樣式就可以滿足,使用方法跟web上一樣。
<view class="marquee"> <text>這是一段滾動的文字</text> </view>
樣式類,from to 來定義動畫的開始結束,這裡是從螢幕最右端向左滑,觸及到最左側後重新開始新一輪動畫。
@keyframes translation { from { margin-left: 750rpx; //從螢幕最右端開始 } to { margin-left: 0px; } } .marquee{ white-space: nowrap; animation-name: translation; //定義動畫的名稱 animation-duration: 3s; animation-iteration-count: infinite; animation-timing-function: linear; }
如果想要的效果是滑動到左側之後,文字繼續左滑,直到全部消失,再從最右開始動畫的,那麼就需要再加上文字的長度,這裡需要去計算文字的長度,使用SelectorQuery 物件例項來拿到文位元組點的寬度。在頁面首次渲染完畢onRwww.cppcns.com
onReady: function () { let query = wx.createSelectorQuery(); query.select('.marquee').boundingClientRect(); query.exec((res) => { if (res[0]) { this.setData({ marqueeWidth: res[0].width }) } }) }
然後使用css var() 函式插入定義的屬性值,到結束的位置處,讓它走完整個螢幕以及自身文字的長度。定義一個名為 "--marqueeWidth" 的屬性,然後在wxss樣式檔案裡使用var()函式呼叫該屬性:
<view class="marquee" style="--marqueeWidth:-{{marqueeWidth}}px"> <text>這是一段滾動的文字</text> </view> wxss樣式裡: @keyframes translation { from { margin-left: 750rpx; } to { margin-left: var(--marqueeWidth); } }
這是通過css的方式實現的,非常方便,但是會出現在部分機型上適配的問題,還有一種是通過Animation動畫實現。
animation實現
通過animation動畫例項來完成動畫,一開始讓檢視位於螢幕右側超出螢幕的。
<view class="marquee2" bindtransitionend="animationend" animation="{{animationData}}"> <text>這是一段滾動的文字</text> </view> .marquee2{ display: inline-block; white-space: nowrap; margin-left: 750rpx; }
同樣這裡計算了文字的長度,通過Animation.translate(number tx,number ty)平移屬性進行移動操作,直至移出整個螢幕。在一組動畫完成之後,呼叫bindtransitionend回撥,再一次去執行動畫,
this.animation = wx.createAnimawww.cppcns.comtion({ duration: 3000,timingFunction: 'linear' }); var query = wx.createSelectorQuery(); query.select('.marquee2').boundingClientRect(); query.exec((res) => { if (res[0http://www.cppcns.com]) { this.setData({ marqueeWidth: res[0].width //文字長度 },() => { this.doAnim() }) } }) doAnim: functionhttp://www.cppcns.com () { //向左滾動到超出螢幕,這裡臨時寫死的螢幕寬度375px this.animation.translate(-this.data.marqueeWidth - 375,0).step(); setTimeout(() => { this.setData({ animationData: this.animation.export(),}); },10) }
在第一次動畫結束之後,重新開始,通過http://www.cppcns.comanimationend監聽動畫結束,然後再次執行。
animationend() { //復位 this.animation.translate(0,0).step({ duration: 0 }); this.setData({ animationData: this.animation.export() },() => { //重新開始動畫 this.doAnim() }); }
這個動畫在小程式開發工具上執行會有動畫突然暫停的現象,可以用手機試下的。
相對而言是比較容易實現的,而且走馬燈的效果也是我們在專案中經常會用到的,正好也可以熟悉下小程式的動畫的。
總結
到此這篇關於微信小程式實現走馬燈效果例項的文章就介紹到這了,更多相關小程式走馬燈效果內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!