赞
踩
正常情况下来说,使图片高度跟着宽度变化只需要不给图片高度,只设置高度就行了,但在uniapp不是,这头疼玩意
- <template>
- <div class="banner">
- <center>//center标签,使内容居中
- <image src="/static/bg.jpg" alt="">
- </center>
- </div>
- </template>
- <style>
- .banner image {
- width: 95vw;
- margin-top: 3vh;
- }
- </style>
在代码中我给图片宽度为设备宽度的95%,高度不设置,正常情况下图片的高度会随着宽度自适应而变化,但uniapp不是
可以看到图片的高度是固定的已经产生明显变形,随后右击图片点检查使发现这个,应该是uniapp编译时给图片设置的默认高度
只需要把代码改成以下即可
- <template>
- <div class="banner">
- <center>//center标签,使内容居中
- <image src="/static/bg.jpg" alt="">
- </center>
- </div>
- </template>
- <style>
- //.banner image {
- // width: 95vw;
- // margin-top: 3vh;
- //}
- .banner {
- margin-top: 3vw;
- width: 100%;
- height: 0;
- padding-bottom: 70%;
- /*根据图片宽高比计算出的高度占比*/
- position: relative;
- overflow: hidden;
- /* 防止单独设置 paddingBottom 值的情况下,图片超出容器造成的影响 */
- }
-
- .banner image {
- position: absolute;
- left: 0;
- /*防止图片超出容器影响布局*/
- width: 100%;
- height: 100%;
- object-fit: contain;
- /*根据图片本身宽高比自适应*/
- }
- </style>

然后图片就不会变形了,再根据需要的样式微调就行了
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。