1. 程式人生 > >微信小程式,新新增的元素保持再底部

微信小程式,新新增的元素保持再底部

歡迎來前群裡探討技術QQ:454891743

點選新增按鈕,新新增的元素保持在底部小demo的實現

WXML程式碼:

<!--index.wxml-->
<button type="primary" bindtap="addItemFn">新增</button>
<scroll-view class="scroll" scroll-y="true" scroll-top="{{scrollTop}}" >
  <view class="classname"></view>
  <block wx:for="{{lists}}" wx:key="*this">
    <view class="item" data-index="{{index}}" id="item{{index}}">item {{index}}--{{item.place}}</view>
  </block>
</scroll-view>

WXSS程式碼:
page{height: 100%;}
.scroll{height:400rpx; border: 2px solid #f00;}
.item{ background: #ddd; margin: 10px 0; height: 40px;}
JS程式碼:
//獲取應用例項
var app = getApp()
Page({
  data: {
    lists: [
      { place: "北京" },
      { place: "深圳" },
      { place: "上海" },
      { place: "廣州" },
      { place: "珠海" }
    ],
    //記錄item個數
    itemCount: 5,
    scrollTop: 100,//設定滾動條到頂部的距離

  },
  //事件處理函式
  addItemFn: function () {
    var {lists, itemCount} = this.data;
    var newData = { place: "default" };
    lists.push(newData);
    this.setData({
      lists: lists,
      itemCount: itemCount,
    })
//單獨拿出來用setData 放一個裡會出現問題

    this.setData({
      scrollTop: this.data.scrollTop + 50 // 50代表你要新增的元素的高度
    })
  },
})