uniapp微信小程序css中background-image失效问题

项目场景:

提示:这里简述项目相关背景:

在用uniapp做微信小程序的时候,需要一张背景图,用的是当时做app的时候的框架,但是,在class的样式中background-image失效了,查了后才知道,微信小程序不支持在class中使用background-image,但是可以在标签中使用,而且需要图片路径是base64编码格式的。


解决方案:

提示:这里填写该问题的具体解决方案:

1:图片转换base64编码的工具

javascript 复制代码
npm i image-tools --save

//引入使用
import { pathToBase64, base64ToPath } from 'image-tools'

2:使用函数进行转换

javascript 复制代码
//this.imgUrl 图片路径 /static/img/bg1.png
pathToBase64(this.imgUrl).then(res=>{
    this.bgImgBase64=res
})

3:在标签中使用

html 复制代码
//width height 要设置 
/*
background-attachment 属性值说明
background-attachment 属性有三个主要的可选值,每个值对应不同的效果:
scroll:默认值,背景图像会随着页面内容滚动。
fixed:背景图像固定在视窗中,不会随页面滚动。
local:背景图像与元素内容一起滚动,但仅限于该元素的滚动区域内。
*
/

<view 
	:style="{
		width:'100%',
		height:'100%',
		backgroundImage:'url('+bgImgBase64+')',
		backgroundRepeat: 'no-repeat',
		backgroundPosition: 'center',
		backgroundSize: '100% 100%',
		backgroundAttachment: 'fixed',
	}"
	class="index-content">
......
</view>

4:效果图

相关推荐
丨我是张先生丨18 小时前
日语单词 Web Page
前端·css·css3
吃西瓜不吐籽_21 小时前
2026 届前端校招冲刺:2 万字高频面试题库(含详解、追问与评分标准)
前端·javascript·css·typescript·前端框架·es6
Csvn2 天前
CSS :has() 选择器实战:没有它之前我们写了多少冗余 JS
前端·css
tcdos3 天前
不止扫码 — 微信生态深度融合(登录 + 支付 + 消息)
后端·微信小程序
用户059540174463 天前
大模型长上下文遗忘排查实录:用 Playwright 自动化测试,揪出了 90% 的存储序列化 bug
前端·css
小徐_23333 天前
Wot UI 2.2.0 发布:Button 新增 subtle,VideoPreview 预览体验继续增强
前端·微信小程序·uni-app
天蓝色的鱼鱼4 天前
关于 CSS 你可能不知道的属性,但关键时刻很有用
前端·css
用户059540174464 天前
向量库静默丢数据踩坑实录:Playwright 端到端测试让我排查了72小时
前端·css
ZhengEnCi5 天前
Q06-导航按钮高级拟态玻璃效果构建完全指南
前端·css
宸翰5 天前
解决 uni-app App 端 vue-i18n 占位符丢失:封装跨端可用的 tf 格式化方法
前端·vue.js·uni-app