制作收藏的点击收藏、取消收藏的图标切换效果
效果:
vue:
<template>
<van-action-bar>
<van-action-bar-icon icon="chat-o" text="客服" color="#ee0a24" />
<van-action-bar-icon icon="cart-o" text="购物车" to="/cart"/>
<van-action-bar-icon icon="star-o" text="收藏" @click="handelCollectAdd" />
<van-action-bar-button type="warning" text="加入购物车" @click="handelCartAdd"/>
<van-action-bar-button type="danger" text="立即购买" />
</van-action-bar>
</template>
js 代码:点击切换效果
let status = true
const p = document.getElementsByClassName('van-action-bar-icon')
const handelCollectAdd = () => {
if (status) {
status = false
// console.log(p[2].childNodes[0])
p[2].childNodes[0].classList.replace('van-icon-star-o', 'van-icon-star')
p[2].childNodes[1].data = '已收藏'
console.log(p)
} else {
status = true
p[2].childNodes[0].classList.replace('van-icon-star', 'van-icon-star-o')
p[2].childNodes[1].data = '收藏'
}
}
根据类名获取元素 getElementsByClassName,得到数组,根据数组下标找到‘收藏’的位置,打印输出找到:
同时看到控制该图标的样式:
所以,p[2].childNodes[0] 找到需要修改的icon图标,使用html新增classList 操作类名,
- classList.replace( oldClassName,newClassName );
类名替换
css:
:deep(.van-icon-star:before) {
content: '\e727';
color: #ff5000;
}
:deep(.van-icon-star-o:before){
content: '\e722'
}