微信小程序實現(xiàn)跑馬燈效果

網(wǎng)上很多實現(xiàn)跑馬燈的文章,但是很多發(fā)現(xiàn)都是不行的,之一就是文字寬度居然是通過字符數(shù)*文字size計算,明顯是不準確的計算方式。我看了下,發(fā)現(xiàn)可以通過計算控件寬度來精確計算文字寬度,這樣實現(xiàn)的跑馬燈是比較完善的。

成都做網(wǎng)站、網(wǎng)站建設介紹好的網(wǎng)站是理念、設計和技術的結合。創(chuàng)新互聯(lián)擁有的網(wǎng)站設計理念、多方位的設計風格、經(jīng)驗豐富的設計團隊。提供PC端+手機端網(wǎng)站建設,用營銷思維進行網(wǎng)站設計、采用先進技術開源代碼、注重用戶體驗與SEO基礎,將技術與創(chuàng)意整合到網(wǎng)站之中,以契合客戶的方式做到創(chuàng)意性的視覺化效果。

效果如下:

微信小程序實現(xiàn)跑馬燈效果

實現(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é)點選擇器
  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) {
   //設置循環(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();
  });
 }
 })

源碼下載:跑馬燈效果

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

網(wǎng)頁名稱:微信小程序實現(xiàn)跑馬燈效果
URL標題:http://muchs.cn/article16/iiojgg.html

成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站制作網(wǎng)站排名、全網(wǎng)營銷推廣、自適應網(wǎng)站品牌網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經(jīng)允許不得轉載,或轉載時需注明來源: 創(chuàng)新互聯(lián)

成都seo排名網(wǎng)站優(yōu)化