uniapp通过循环实现不同的背景图和设置每个元素中不同尺寸的图片功能

        为了页面能给人们带来视觉上的惊艳,往往设置不同的背景图。通过循环来实现一系列的操作,后台数据也不会返回你背景图的地址,这时就需要我们通过动态来设置style的属性。

        效果:

        

当客户要求我们实现上图的效果的时候,我们只能通过设置

:style="{backgroundImage:'url('+背景色数组[下标]+')'}”来实现,直接上例子:

<view class="main">
	<view class="grade">
		<view class="gradelist" v-for="(item,index) in gradelists" :key="index" :style="{backgroundImage:'url('+imagesrc[index]+')'}">
			<view class="toplist">
				<image :src="item.url" ></image>
			</view>	
		</view>
	</view>
</view>

export default {
	data() {
		return {
			gradelists:[
				{
					url:'../../static/images/fulibox.png',
				},
				{
					url:'../../static/images/yijilogo.png',
					
				},
				{
					url:'../../static/images/erjilogo.png',
				},
				{
					url:'../../static/images/sanjilogo.png',
				},
				{
					url:'../../static/images/sijilogo.png',
				},
				{
					url:'../../static/images/wujilogo.png',
				},
				{
					url:'../../static/images/liujilogo.png',
				}
				],
				//背景图路径
				imagesrc:[
					'../../static/images/fulibg.png',
					'../../static/images/yijibg.png',
					'../../static/images/erjibg.png',
					'../../static/images/sanjibg.png',
					'../../static/images/sijibg.png',
					'../../static/images/wujibg.png',
					'../../static/images/liujibg.png'
				]
			}
		}

        其中,gradelists:代表所有数据,imagesrc:代表所有背景图

        通过循环我们可以获取到每个容器的下标(index),通过index将背景图与容器(div)一一对应起来。

        不难发现,除了背景图不同,容器内的logo高度(height)也不同,想要修改每个容器中不同的logo大小,就需要通过css的 类名:first-child 和 类名:nth-child(n)来修改

        类名:first-child :来修改第一个盒子的样式

        类名:nth-child(n) :来修改每个盒子不同的元素 , n=1,及第一个元素

//设置第一个盒子的样式
.gradelist:first-child{
		width: 100% !important;
		height: 190rpx !important;
		background-repeat: no-repeat;
		background-size: cover;
		box-sizing: border-box;
		padding: 23rpx 43rpx 26rpx 18rpx;
		display: flex;
		
		//设置第一个盒子内的图片
		image{
			height: 45rpx!important;
		}
	}
// 设置第三个盒子内图片的大小
.gradelist:nth-child(3){
	image{
		height: 58rpx!important;
	}
} 
// 设置第四个盒子内图片的大小
.gradelist:nth-child(4){
	image{
		height: 63rpx!important;
	}
} 
// 设置第五个盒子内图片的大小
.gradelist:nth-child(5){
	image{
		height: 68rpx!important;
	}
} 
// 设置第六个盒子内图片的大小
.gradelist:nth-child(6){
	image{
		height: 73rpx!important;
	}
} 
// 设置第七个盒子内图片的大小
.gradelist:nth-child(7){
	image{
		height: 77rpx!important;
	}
}

        代码只是部分代码,只是为了让大家清楚明了如何使用类名:first-child 和 类名:nth-child(n),具体所需的样式还需要自己来调整!

  • 2
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值