案例:
做一个以图片为背景, 上面放有标题的菜单.
在 UniAPP 中,<image> 标签用于显示图片,但它不支持直接嵌套其他标签. --所以不能使用 Image 直接嵌套
一. 静态背景
- 可以在一个 view 元素上使用 style 属性,并通过 background-image 样式来设置背景图片。例如:
.background-image-view {
width: 100%;
height: 200px; /* 根据你的需求设置高度 */
background-image: url('/static/your-image.png');
background-size: cover; /* 或者 'contain', 根据你的需求设置 */
background-position: center;
}
- 使用 image 标签和绝对定位.
可以通过绝对定位来将 image 标签放置在 view 标签的背后。
<view class="container-view">
<image class="background-image" src="/static/your-image.png" mode="aspectFill"></image>
<!-- 其他内容 -->
<text>这是覆盖在图片上的文字</text>
</view>
CSS布局
.container-view {
position: relative;
width: 100%;
height: 200px; /* 根据你的需求设置高度 */
}
.background-image {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
z-index: -1; /* 确保图片在其他内容之下 */
}
二. 动态背景
使用内联 :style 修改 backgroundImage 作为背景图片, 以实现背景图片的动态切换;
<view class='cover' :style="{ backgroundImage: 'url(' + myImg + ')' }"> 内容 </view>
data() {
myImg : '././static/home/bg.png',
}
CSS
. cover {
background-repeat: no-repeat;
background-size: 100% 100%;
}