1. 程式人生 > 實用技巧 >關於微信小程式的一些知識點

關於微信小程式的一些知識點

一、自定義背景導航

關於微信小程式的自定義導航,考慮到iPhoneX以上的裝置,就要考慮到導航欄的高度。這就要用到微信小程式的APIwx.getSystemInfoSync()

getSystemInfoSync()方法中statusBarHeight 就能獲取狀態列的高度,然後就可以計算標題的top值。

<!-- 自定義導航 -->
<!-- widthFix 縮放模式,寬度不變,高度自動變化,保持原圖寬高不變 -->
<image class="top-bg" src="{{bgImg}}" mode="widthFix"/>

<view 
class="top" style="height: {{statusBarHeight + 44}}px;"> <view class="navigation" style="top: {{statusBarHeight}}px;"> <image src="/image/back.png" class="icon-back" bindtap="goBack" wx:if="{{showBack}}"/> <view class="navigation-text">{{title}}</view> </view>
</view>
.top-bg{
  width: 100%;
  height: 460rpx;
  position: fixed; // 背景圖片 fixed
  left: 0;
  top: 0;
  z-index: -1;
}

.top{
  width: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 999;
}
.navigation{
  width: 100%;
  position: absolute;
  left: 0;
  z-index: 10;
}
.icon-back{
  width: 14px;
  height
: 14px; padding: 15px 20px; position: absolute; top: 0; left: 0; z-index: 20; } .navigation-text{ width: 100%; line-height: 44px; text-align: center; font-size: 34rpx; color: #fff; }

JS 部分

 /**
   * 元件的初始資料
   */
  data: {
    bgImg:"/image/....png",
    statusBarHeight:wx.getSystemInfoSync().statusBarHeight
  },

二、根據文字長度 計算滾動時間 自適應滾動

<view class="bulletin-board" style='--marqueeWidth--:{{marqueeWidth}}rpx;--marqueeSeconds--:{{marqueeSeconds}}s'>
    <!-- 公告資訊展示 -->
    <view class="notice-content">{{msg}}</view>
</view>
.bulletin-board{
  overflow: hidden; //必須的屬性
}
.notice-content{
  font-size: 26rpx;
  color: #333;
  transform: translateX(0);
  white-space: nowrap; // 必須的屬性 阻止換行
  animation: myfirst var(--marqueeSeconds--) linear infinite;
}
@keyframes myfirst{
  from {
    transform: translateX(100%)
  }
  to {
    transform: translateX(var(--marqueeWidth--))
  }
}

JS部分

 /**
   * 生命週期函式--監聽頁面初次渲染完成
   */
  onReady: function () {
    this.setTextWidth();
  },  

  setTextWidth(){
      let msgWidth = (this.data.msg.length)*26
      let query = this.createSelectorQuery();  // 在自定義元件或包含自定義元件的頁面中,應使用this.createSelectorQuery()來代替。
      query.select('.notice-content').boundingClientRect(rect => {
        if (rect) {
          console.log(rect)
          let w = wx.getSystemInfoSync().screenWidth  // 上文提到過  screenWidth 螢幕寬度
          let scrollDistance = w + rect.width; // rect.width就是notice-content的view的寬度,由於其中文字強制不換行。
          this.setData({
            marqueeWidth: -msgWidth, // 負值就是移動位置的絕對位置,負的寬度剛好將所有文字完全向左移出
            marqueeSeconds: scrollDistance * 0.02 // 計算滾動時間,如果同時使用多個元件儲存這幾個不同寬度內容的滾動速度幾乎一致
          });
        }
      }).exec();
  },