CSS/WXSS变量嵌套(wx:for中使用)

直接说重点

在wx:for循环中使用{{}}来获取对应的数组的值,在定义wx:for-index="index"之后,可以直接使用{{array[index]}}实现嵌套。获取到js的data中array数组中下标为(wx:for中index)对应的值。

需求

在微信小程序页面布局文件中,需要不确定数量的相同布局组件,而且每个组件的大小根据其接收到的图片大小而不同,固定宽度为334rpx,长度自调节。

思路

首先通过根据通过后台获取到的数据,使用wx:for循环渲染,在其中的image组件上设置bindload函数,在js中获取图片的分辨率,然后计算宽高比,再根据固定的宽度计算出每个组件特定的高度,保存到数组中,然后在image组件中通过style属性读取数组对应的元素的值。

难点

wxml通过{{}}获取js中变量的值,但是获取数组中特定元素的值没有具体规则,最初想通过wx:for-index="index"获取当前循环的下标值,使用{{array[{{index}}]}}获取js中array[index]的值,但是这种嵌套是不被允许的,一番格式摸索后发现直接使用{{array[index]}}就可以获取到对应的值了,先获取index的值,假设index为1,这里实际传到js中的变量名是array[1]。

前端页面wxml

 <view class="list_view"> 
      <view wx:for="{{list_array_right}}" wx:key="id" class="list" id="{{item.id}}" catchtap="list_onclick" style="height:calc{{title_img_height[index]}}rpx;">
        <image class="list_img" mode="aspectFit" src="你的域名" wx:for-index="index" bindload="get_img_size" style="height:{{title_img_height[index]}}rpx;"></image>
        <text>{{title_img_height_right[index]}}</text>
        <text class="list_title">{{item.title}}</text>
        <view class="author">
          <image class="author_head" src="{{item.head_img}}"></image>
          <text class="author_name">{{item.author_name}}</text>
          <view class="like">
            <image class="like_icon" src="/drawable/like_off.png"></image>
            <text class="like_num">{{item.like_num}}</text>
          </view>
        </view>
      </view>
    </view>

js

get_img_size(e){
    var tempWidth = e.detail.width; // 获取图片实际宽度
    var tempHeight = e.detail.height; // 获取图片实际高度
    var height = (tempHeight*750.0)/tempWidth;//计算显示高度
    var height_list = this.data.title_img_height_left||[];
    height_list.push(height);
    this.setData({
      title_img_height:height_list
    })
  }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值