swiper小程序轮播图片自适应

版权声明:一切都是为了学习记录,随便转载。 https://blog.csdn.net/Gjanuary/article/details/79429840
思路:
	1.获得屏幕宽度
	2.获得图片宽度和高度
	3.进行比例换算,给swiper高度,图片给widthFix model即可
------------------------------------------------------
代码如下:
	1.app.js中获取屏幕尺寸:
		onLaunch: function () {
			  wx.getSystemInfo({
				success: function (res) {
					console.log(res.windowWidth)
					console.log(res.windowHeight)
					// 进行保存屏幕的高度和宽度
					wx.setStorageSync('phoneattr', res)
					
				}
			  })
		},
	2.index.js中,获取图片尺寸,并作出相应的比例换算:
		Page({
			data: {
				movies: [
					{ url: 'https://ss0.bdstatic.com/-0U0bnSm1A5BphGlnYG/tam-ogel/af23a2a898acc57e15cdeee31145d59a_259_194.jpg' },
					{ url: 'https://ss0.bdstatic.com/-0U0bnSm1A5BphGlnYG/tam-ogel/af23a2a898acc57e15cdeee31145d59a_259_194.jpg' },
				] ,  
			},
			onLoad: function (options) {
				var that = this
				var lunboimg = [
					{ url: 'https://ss0.bdstatic.com/-0U0bnSm1A5BphGlnYG/tam-ogel/af23a2a898acc57e15cdeee31145d59a_259_194.jpg' },
					{ url: 'https://ss0.bdstatic.com/-0U0bnSm1A5BphGlnYG/tam-ogel/af23a2a898acc57e15cdeee31145d59a_259_194.jpg' },
				 ];
				  // 获得一个图片的高度即可
				  wx.getImageInfo({
					  src: lunboimg[0].url,
					  success: function(res){
						  // 获取当前屏幕的宽度
						  var attr = wx.getStorageSync('phoneattr')
						  console.log("获取当前屏幕的宽度");
						  console.log(attr.screenWidth);
						  console.log(res.width);
						  console.log(res.height);
						  var imgHeight = (res.height * attr.screenWidth)/(res.width)
						  that.setData({
							  imgWidth: attr.screenWidth,
							  imgHeight: imgHeight
						  })  
					  }
				  }) 
			  }  
		})
	3.index.wxml 中代码:
		<!-- 包括主菜推荐,活动推选,店铺介绍,联系方式。。。 进入点餐操作-->
		<view class="contain">
			<!--主菜推荐-->
			<swiper style="width:{{imgWidth}}px;height:{{imgHeight}}px" class="swiper" indicator-dots="true" autoplay="true" interval="5000" duration="1000">    
				<block wx:for="{{movies}}" wx:for-index="index">    
					<swiper-item>    
						<image src="{{item.url}}"  class="slide-image" mode="widthFix"/>    
					</swiper-item>    
				</block>    
			</swiper> 
		</view>
	4.index.wxss 中代码:	
		/**index.wxss**/
		.swiper{
			padding: 0;
			margin: 0;
		}
		.swiper image {
			width: 100%;
			height: 100%;
		}
		.shopanduser{
			width: 100%;
		}
		.shop,.user{
			width: 50%;
			float: left;
		}
	5.效果图如下:
		
	
		

猜你喜欢

转载自blog.csdn.net/Gjanuary/article/details/79429840
今日推荐