动态设置背景颜色
静态设置背影颜色的方式比较简单,只需要在app.wxss中统一设置page样式。
page { background-color: rgba(250,250,250,0.90); }
全局变量的使用
然而我们想动态设置背景颜色,即让用户在给定的背景颜色中做出选择。首先通过查阅资料了解到微信小程序是可以设置全局变量的,要在app.js中添加globalData来实现,具体如下:
var backcolor = "#3197ed"//设置初始值 var background globalData: { background : backcolor }
而全局变量是可以在别的地方动态修改的,这就与我们想要的效果非常贴切了。修改动态变量的方法如下:
var app = getApp();//在开头这样写 …… red: function () { background = "#F4A7B9" this.setData({ background: background }) app.globalData.background = background//实现全局变量的修改,此时app.globalData.background的值为"#F4A7B9" },
修改背景颜色函数的编写
在介绍完全局变量后接下来就是具体的函数实现了,以js中两个具体函数为例:
red: function () { background = "#F4A7B9" this.setData({ background: background }) app.globalData.background = background wx.setNavigationBarColor({//设置导航栏颜色 frontColor: '#000000',//注意frontColor的值只能为000000或者111111 backgroundColor: app.globalData.background }); }, moren: function () {//还原默认的函数 background = "#3197ed" this.setData({ background: background }) app.globalData.background = background wx.setNavigationBarColor({ frontColor: '#000000', backgroundColor: app.globalData.background }); }
在设置完全局变量background之后,我们是可以在.wxml中调用的,这样通过使用公共属性style

在需要显示背景颜色的页面加入style来动态显示背景颜色
<view> <button class='btn1' style="background:#F4A7B9" bindtap="red">变红</button> </view>
这样就可以动态的修改背景颜色了!
文章来源: https://blog.csdn.net/weixinmp2019/article/details/91375078