持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第1天,点击查看活动详情
刚发的时候没看到活动,凑个热闹……
今儿的创作欲很高涨哈 :D
这也是在群里看到的,群友问如何在滑动(或者自动滑动)的时候背景颜色能跟着变
正好之前做过这个需求,也分享一下
首先,页面的组成分为三部分: 自定义navbar、 页面背景、 轮播图
大致如下(看重点,不要照抄):
<u-navbar :background="navBackground"></u-navbar>
<view class="header-wrap" :style="{'--bg-color':bgColor}">
<u-swiper :list="swiperList" @change="changeSwiper"></u-swiper>
</view>
对应的,我们需要初始化一下
data() {
return {
navBackground: {backgroundColor: '#fff'},
bgColor: '#fff',
swiperList: [
{
image: 'xxx',
bgColor: '#000'
}
// 这只是个结构的示意,实际上这里留空也行
]
}
}
css部分
/* 这里我自己需要,所以用了伪类,只看var部分即可 */
.header-warp::after {
background-color: var(--bg-color);
}
这样基本上就完成了, 我们来看一下逻辑, 上边实际就是一个自定义的导航u-navbar,一个包裹着轮播图的背景和轮播图自己;
当轮播图change的时候,触发changeSwiper
通过获取到的轮播的index,取出来后端传来的背景色,再分别赋值给导航栏和轮播图的背景
changeSwiper(index) {
let bgColor = this.swiperList[index]['bgColor'];
this.bgColor = bgColor;
this.navBackground = { backgroundColor: bgColor };
}
来看看最终的效果:
实际上如果你没用uView,甚至也不是uni-app,只要你是vue开发的 这逻辑都适用,主要就是一个css的传值,解决这个就都好办。