为了页面能给人们带来视觉上的惊艳,往往设置不同的背景图。通过循环来实现一系列的操作,后台数据也不会返回你背景图的地址,这时就需要我们通过动态来设置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),具体所需的样式还需要自己来调整!