图片自适应在网站上是内置好的,只需要设置宽度即可,但在微信小程序非要做一个封装,高度不是随宽度自适应,真是操蛋,不过谁叫在人家的平台的搞呢,还是不得不屈服于小马哥的淫威啊。。
在微信小程序上实现图片自适应需要配合javascript脚本,也就是需要动态计算才能实现,具体修改如下:
先看下view层是什么样的
<view class="zh-carousel" style="margin-top: {
{
carouselMarginTop}}rpx"> <swiper indicator-dots="true" autoplay="true" interval="4000" duration="500" class="zh-swiper" style="height: {
{
carouselHeight}}px"> <swiper-item class="zh-swiper-item" wx:for="{
{carouselList}}" wx:key="index"> <image src="{
{ item.image }}" mode="widthFix" bindload="adaptCarouselHeight">
image>
swiper-item>
swiper>
view>
因为设置了导航样式为自定义,所以需要给轮播图加个margin-top值 ,不然会被小程序功能按钮遮挡
{
"usingComponents": {
}, "navigationStyle": "custom" }

下面看下数据是如何计算的(注释很详细),如果不想细看的话,直接对着撸就行了
Page({
data: {
list: [], carouselList: [ {
image: '../../images/img-wx-gzh.png'}, ], carouselMarginTop: 0, // 这两个初始值必须要设置 carouselHeight: 0 }, onLoad: function() {
this.adaptCarouselMarginTop(); // 适配轮播图外间距 }, // 适配轮播图外间距 adaptCarouselMarginTop() {
let systemInfo = wx.getSystemInfoSync(), pxToRpxScale = 750 / systemInfo.windowWidth, // px转换到rpx的比例 ktxStatusHeight = systemInfo.statusBarHeight * pxToRpxScale, // 状态栏高度 navigationHeight = 44 * pxToRpxScale; // 导航高度,44是大概估值 this.setData({
carouselMarginTop: navigationHeight + ktxStatusHeight + 10 // 10是一个预估值,可根据呈现效果修改 }); }, // 适应轮播图高度 adaptCarouselHeight(e) {
let imgWidth = e.detail.width, // 原图宽高 imgHeight = e.detail.height, screenWidth = wx.getSystemInfoSync().screenWidth; // 手机屏幕宽度 let ratio = (screenWidth - screenWidth/750*60) / imgWidth; this.setData({
carouselHeight: imgHeight * ratio }); } }
欢迎关注:https://www.fenxianglu.cn/
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/227523.html原文链接:https://javaforall.net
