微信小程序動畫:高度漸變,left漸變


  今天在測試微信小程序動畫的時候遇到了坑,需求是這樣的點擊時子元素從外部滑動回來,父元素的高度跟隨子元素的高度改變。

 

  實現子元素left為0並不復雜,但是改變父元素box的高度的時候卻遇到了坑,因為是需要跟隨子元素right的高度來改變父元素box的高度的,並且子元素right的高度不確定,我們需要先獲取子元素的高度。

  在改變高度的時候出錯了,高度未改變。在測試時發現

    var box = wx.createAnimation(option); // 創建動畫
    var obj = wx.createSelectorQuery();
    obj.select('.anr').boundingClientRect(function (rect) {//獲取子元素高度
      box.height(rect.height).step();//改變父元素高度
      console.log(1);
    }).exec();
    console.log(2);
    that.setData({
      box: box.export()
    });

  

  先打印的竟然是2,原來是一個異步操作,這就可以理解為什么執行無效了。改成這樣

    obj.select('.anr').boundingClientRect(function (rect) {//獲取子元素高度
      var box = wx.createAnimation(option); // 創建動畫
      box.height(rect.height).step();//改變父元素高度
      that.setData({
        box: box.export()
      });
    }).exec();

  想着應該沒問題了,但是遇到了另外一個坑,父元素的高度一下子變成了預設的效果,並沒有Animation的漸變效果。本身父元素的高度是由left這個子元素撐起來的,給父元素預設一個高度這個問題就解決了。漸變效果就實現了。

   源碼解析

wxml

<view class="box" animation="{{box}}">
  <view class="anl">left</view>
  <view class="anr" animation="{{anr}}">right</view>
</view>
<button bindtap="add" wx:if="{{down}}">goDown</button>
<button bindtap="goback" wx:else>goBack</button>

 

wxss

/* pages/userinfo/index.wxss */
.box{
  position: relative;
  height: 200rpx;
  overflow: hidden;
  text-align: center;
  color: white;
  font-size: 120rpx;
}
.anl{
  height: 200rpx;
  background-color: red;
}
.anr{
  background-color: green;
  height: 400rpx;
  width: 100%;
  position: absolute;
  left: 100%;
  top: 0;
}
.add{
  background-color: yellow;
  height: 100rpx;
}

  

js

// pages/userinfo/index.js
Page({

  /**
   * 頁面的初始數據
   */
  data: {
    box: {},
    anr: {},
    down:true
  },
  add: function () {
    this.setData({
      down: false
    });
    var that = this;
    let option = {
      duration: 1000, // 動畫執行時間
      timingFunction: 'ease-in' // 動畫執行效果
    };
    var anr = wx.createAnimation(option);// 創建動畫
    this.anr=anr;
    anr.left(0).step();
    that.setData({
      anr: anr.export()
    });
    var obj = wx.createSelectorQuery();
    obj.select('.anr').boundingClientRect(function (rect) {//獲取子元素高度
      var box = wx.createAnimation(option); // 創建動畫
      that.box=box;
      box.height(rect.height).step();//改變父元素高度
      that.setData({
        box: box.export()
      });
    }).exec();
  },
  goback:function(){
    this.setData({
      down:true
    });
    this.box.height('200rpx').step();
    this.setData({
      box:this.box.export()
    });
    this.anr.left('750rpx').step();
    this.setData({
      anr:this.anr.export()
    })
  }
})

  


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM