看到这个标题的时候,可能有人会问,uni-app 中使用背景图片不是很简单的事情,直接使用 css 就可以了。

没错,如果不考虑多端兼容性的问题,使用起来很简单,如下:

background-image: url(../../static/images/bg.png);
background-size: 100% 100%;
background-position: 50% 50%;
background-repeat: no-repeat;

这样在在 H5 上使用没啥问题,但是在微信小程序中运行会发现报如下错误:

pages/*.wxss 中的本地资源图片无法通过 WXSS 获取,可以使用网络图片,或者 base64,或者使用<image/>标签

这边说的很明白,提供了3种解决方式,笔者推荐使用 image 标签。因为base64还需要本地转换,比较麻烦;而使用网络图片对不同环境需要不同配置。

下面就简单介绍使用 image 标签的方式。

给需要设置背景图片的组件增加样式:

position: relative;
z-index: 0; // 支付宝小程序下背景不生效时,可以加上这个

再在该组件中插入 image 组件:

<image class="image-bg" src="/static/images/bg.png"/>

在 App.vue 中加入 image-bg 样式:

.image-bg {
    position: absolute;
    z-index: -1;
    left: 0;
    right: 0;
    bottom: 0;
    right: 0;
    width: 100%;
    height: 100%;
}

OK,大功告成~~~。

如果觉得我的文章对你有用,请点个赞