实现效果如下,实现多选和取消的功能:
定义一个数组为lists,用来存放上面列举的列表,数据格式如下,其中status为标识该图片是否已选:
lists: any = [
{
id: 1,
img: './assets/img/pic/c1.png',
name: '展会',
status: true
},
{
id: 2,
img: './assets/img/pic/c2.png',
name: '讲座',
status: false
},
{
id: 3,
img: './assets/img/pic/c3.png',
name: '演唱会',
status: false
}
]
一、页面显示 html
<div class="r-cnt">
<div class="r-item" *ngFor="let i of lists" (click)="chooseItems(i.id)">
<img [src]="i.img" class="r-pic-bg" />
<!--选中和未选中两个图标,状态切换-->
<img [src]="pick" class="r-pic-icon" *ngIf="i.status==true" /> <!--选中时显示-->
<img [src]="nopick" class="r-pic-icon" *ngIf="i.status==false" /> <!--未选中时显示-->
<p class="r-label">{{i.name}}</p>
</div>
</div>
二、逻辑控制 ts
chooseAry: any = []; //最终选择的图片,存储id值
lists: any = [
{
id: 1,
img: './assets/img/pic/c1.png',
name: '展会',
status: true
},
{
id: 2,
img: './assets/img/pic/c2.png',
name: '讲座',
status: false
},
{
id: 3,
img: './assets/img/pic/c3.png',
name: '演唱会',
status: false
}
]
pick: any = './assets/img/icon/ischoose.png'; //选中的图标
nopick: any = './assets/img/icon/nchoose.png'; //未选中的图标
//当点击图片时,会进行状态切换
chooseItems(id) {
//循环遍历列表数组
for(let i = 0; i < this.lists.length; i++) {
//匹配点击的item和数组里面的对应
if(id == this.lists[i].id) {
//如果点击的item为选中状态就更改为未选中状态,同时从数组里去掉对应的元素,反之...
if(this.lists[i].status == true) {
this.lists[i].status = false;
this.del(this.chooseAry,id);
} else {
this.lists[i].status = true;
this.chooseAry.push(id);
}
}
}
console.log(this.chooseAry); //最终的选择类型数组
}
//删除数组中的某一个元素
del(ary, el){
const index = ary.indexOf(el);
const delEle = ary.splice(index, 1);
return ary;
}
三、样式 css
/*选择内容 S*/
.r-cnt{
padding: 25px 40px;
display: flex;
justify-content: space-between;
flex-wrap: wrap;
}
.r-item{
/* margin-right: 8px; */
/* display: inline-block; */
position: relative;
margin-bottom: 10px;
}
.r-item:nth-child(3n){
margin-right: 0;
}
.r-item img.r-pic-bg{
width: 92px;
height: 92px;
}
.r-item img.r-pic-icon{
position: absolute;
width: 19px;
height: 19px;
top: 5px;
right: 5px;
}
.r-label{
text-align: center;
padding: 3px 0;
font-size: 15px;
font-weight: bold;
}
/*选择内容 E*/