uniapp 开发一款屏幕变红变白
时间: 2025-02-12 17:01:19 浏览: 34
### UniApp 实现屏幕背景色切换
在 UniApp 中实现屏幕背景色的动态切换可以通过 `uni.setNavigationBarColor` 方法来改变导航栏的颜色,并通过修改页面样式属性来调整整个页面的背景颜色。下面是一个完整的例子,展示如何创建一个按钮用于切换页面背景色为红色和白色的动画效果。
#### HTML 结构
定义两个视图组件作为触发器以及设置根容器以便应用全局样式的更改:
```html
<template>
<view class="container">
<!-- 切换按钮 -->
<button type="primary" @click="switchBackgroundColor">点击切换</button>
<!-- 页面内容区域 -->
<view class="content-area"></view>
</view>
</template>
```
#### JavaScript 部分
编写逻辑处理函数,在每次点击时更新状态并调用 API 更改主题配色方案:
```javascript
<script>
export default {
data() {
return {
isRedTheme: false,
};
},
methods: {
switchBackgroundColor() {
this.isRedTheme = !this.isRedTheme;
const newBackground = this.isRedTheme ? "#ff0000" : "#ffffff";
document.body.style.backgroundColor = newBackground;
// 同步修改顶部导航条颜色以匹配整体风格
uni.setNavigationBarColor({
frontColor: this.isRedTheme ? '#ffffff' : '#000000',
backgroundColor: newBackground,
animation: { duration: 500, timingFunc: 'ease-in-out'}
})[^1];
}
}
};
</script>
```
#### CSS 样式表单
为了使过渡更加平滑自然,可以添加一些简单的CSS3转换规则给body标签或其他指定元素上:
```css
<style scoped>
.container {
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
}
.content-area {
width: 90%;
min-height: calc(100% - 80px);
}
/* 添加转场效果 */
body {
transition: background-color .5s ease-in-out;
}
</style>
```
此段代码实现了当用户按下按钮后,能够流畅地在红白两种色调间切换的功能,同时保持良好的用户体验。注意这里使用了 `transition` 来让背景颜色的变化带有渐变效果。
阅读全文
相关推荐













