您好,登錄后才能下訂單哦!
網(wǎng)上很多實(shí)現(xiàn)跑馬燈的文章,但是很多發(fā)現(xiàn)都是不行的,之一就是文字寬度居然是通過字符數(shù)*文字size計(jì)算,明顯是不準(zhǔn)確的計(jì)算方式。我看了下,發(fā)現(xiàn)可以通過計(jì)算控件寬度來精確計(jì)算文字寬度,這樣實(shí)現(xiàn)的跑馬燈是比較完善的。
效果如下:
實(shí)現(xiàn)代碼如下:
wxml:
<view class="rollCon"> <view class='box'> <view class='text'style='left:{{offsetLeft}}px' >{{text}}</view> </view> </view>
wxss:
.rollCon { position: fixed; top: 0; left: 0; width: 100%; height: 60rpx; z-index: 100; background: #fde8c7; font-size: 20rpx; line-height: 60rpx; } .box { width: 100%; position: relative; } .text { white-space: nowrap; position: absolute; top: 0; font-size: 24px; }
js:
Page({ /** * 頁面的初始數(shù)據(jù) */ data: { interval: null, text: '995年JavaScript誕生時如早一年', pace: 1.2, //滾動速度 interval: 20, //時間間隔 size: 24, //字體大小in px length: 0, //字體寬度 offsetLeft: 0, // windowWidth: 0, }, //根據(jù)viewId查詢view的寬度 queryViewWidth: function(viewId) { //創(chuàng)建節(jié)點(diǎn)選擇器 return new Promise(function(resolve) { var query = wx.createSelectorQuery(); var that = this; query.select('.' + viewId).boundingClientRect(function(rect) { resolve(rect.width); }).exec(); }); }, //停止跑馬燈 stopMarquee: function() { var that = this; //清除舊的定時器 if (that.data != null) { clearInterval(that.interval); } }, //執(zhí)行跑馬燈動畫 excuseAnimation: function() { var that = this; if (that.data.length > that.data.windowWidth) { //設(shè)置循環(huán) let interval = setInterval(function() { if (that.data.offsetLeft <= 0) { if (that.data.offsetLeft >= -that.data.length) { that.setData({ offsetLeft: that.data.offsetLeft - that.data.pace, }) } else { that.setData({ offsetLeft: that.data.windowWidth, }) } } else { that.setData({ offsetLeft: that.data.offsetLeft - that.data.pace, }) } }, that.data.interval); } }, //開始跑馬燈 startMarquee: function() { var that = this; that.stopMarquee(); //初始化數(shù)據(jù) that.data.windowWidth = wx.getSystemInfoSync().windowWidth; that.queryViewWidth('text').then(function(resolve) { that.data.length = resolve; console.log(that.data.length + "/" + that.data.windowWidth); that.excuseAnimation(); }); } })
源碼下載:跑馬燈效果
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。