效果图如图:
其中右侧边框线使用伪元素,小图标使用精灵图
<view class="content-box">
<view class="serviceItem" v-for="(item,index) in convenienceServiceList" :key="index">
<view class="serviceTop">
<view class="serviceImg" :style="{backgroundPosition: item.bgPosition}"></view>
<view class="serviceTitle">{{item.serviceTitle}}</view>
</view>
<view class="serviceClassification">
<view class="classificationItem" v-for="ite in item.serviceClassification" :key="ite.id">{{ite.name}}</view>
</view>
</view>
</view>
其中className为‘classificationItem’的就是需要使用伪元素添加右边框和下边框的盒子
.serviceClassification {
display: flex;
flex-flow: row wrap;
width: 100%;
background-color: rgba(255, 255, 255, 1);
border-radius: 12rpx;
.classificationItem {
position: relative;
width: 234rpx;
height: 100rpx;
text-align: center;
line-height: 100rpx;
color: rgba(80, 80, 80, 1);
font-size: 28rpx;
}
//为盒子添加下边框
.classificationItem::after {
content: ' ';
position: absolute;
left: 0;
bottom: 0;
right: 0;
height: 1px;
border-bottom: 1px solid #e5e5e5;
color: #e5e5e5;
transform-origin: 0 100%;
transform: scaleY(0.5);
}
//为盒子添加右边框,这种添加方法的好处是可以自定义边框线的高度和上下左右的位置
.classificationItem::before {
content: '';
position: absolute;
right: 0;
top: calc(50% - 25rpx);
width: 2rpx;
height: 50rpx;
z-index: 1;
background: rgba(229, 229, 229, 1);
}
//如果是3以及3的倍数个盒子,将边框线透明化,即去掉边框线。
.classificationItem:nth-child(3n)::before {
background: rgba(229, 229, 229, 0);
}
}
精灵图的使用
在H5页面可以操作DOM节点的环境下,可以使用以下代码实现精灵图
mounted() {
setTimeout(() => {
// let lis=document.getElementsByClassName('serviceImg');
// for(let i=0;i<lis.length;i++){
// //index就是x坐标,y固定20px
// let index=20 + i*(25+ 15);
// lis[i].style.backgroundPosition=index*-1 + 'px '+'-20px';
// }
}, 500)
},
获取DOM节点列表在mounted之后,使用了setTimeout
但是在微信小程序中,不能对DOM节点进行操作,我的开发需求是需要由后台传值来控制页面上所有显示的内容,所以在HTML代码中添加了 :style="{backgroundPosition: item.bgPosition}" 属性,created的时候获取需要挂载的数据,并添加bgPosition的位置
created() {
this.$api('nearbyServicre.initConvenienceServiceList').then(res => {
this.convenienceServiceList = res.data.items;
this.convenienceServiceList.forEach((c,i)=>{
//index就是x坐标,y固定20px
let index=20 + i*(25+ 15);
this.convenienceServiceList[i].bgPosition = index*-1 + 'px '+'-20px';
})
})
},
css样式
.serviceImg {
width: 50rpx;
height: 50rpx;
margin: 0rpx 12rpx;
background: url(http://10.100.0.120/temp/imgs/sprites-convenienceService.png) no-repeat;
}