h5移动端,类似qq空间、朋友圈不规则图片显示适配功能

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/m0_37992075/article/details/89601521

前言

最近再做个H5移动端社交类型项目的时候,里面有一块 类似朋友圈、qq空间展示的模块,开发的时候发现了一个问题,就是展示用户上传的图片,因为用户上传的图片 可能是相机拍的,可能是截图、可能是网上找的,但是这样会存在一个图片不规则的问题,因为我们是需要展示缩略图的,如果图片的尺寸不满足我们的要求,我们既不能 设置高宽为100%,因为这样可能会存在图片拉伸、挤压的情况;如下是我的解决方法。

不规则素材

效果图

image.png

主要代码

主要html

<!-- _1_2 图片显示数量为1-2张的样式   _3_9 图片显示数量为3-9张的样式 -->
 			<div class="img_body _3_9">
				<div class="img_ctx">
					<img src="imgs/test2.png" alt="">
				</div>
				<div class="img_ctx">
					<img src="imgs/test_phone.png" alt="">
				</div>
				<div class="img_ctx">
					<img src="imgs/test_phone.png" alt="">
				</div>
				<div class="img_ctx">
					<img src="imgs/test2.png" alt="">
				</div>
				<div class="img_ctx">
					<img src="imgs/test_phone.png" alt="">
				</div>
				<div class="img_ctx">
					<img src="imgs/test_phone.png" alt="">
				</div>
				<div class="clear"></div>
			</div>

主要css

			.img_body .img_ctx {
				display: block;
				float: left;
				border-radius: 5px;
				box-shadow: 0px 2px 5px 0px rgba(6, 190, 188, 0.2);
				background-position: center center;
			}
			.img_body .img_ctx img{display: none;}


			.img_body._1_2 .img_ctx {
				width: 49%;
				margin-right: 2%;
				margin-top: 2%;
			}
			.img_body._1_2 .img_ctx:nth-child(2) {
				margin-right: 0;
			}
			
			.img_body._3_9 .img_ctx {
				width: 32.5%;
				margin-right: 1.25%;
				margin-top: 1.25%;
			}
			.img_body._3_9 .img_ctx:nth-child(3){margin-right: 0;}
			.img_body._3_9 .img_ctx:nth-child(6){margin-right: 0;}
			.img_body._3_9 .img_ctx:nth-child(9){margin-right: 0;}

主要js

		$(function(){
			//获取所有没处理的 img
			$.each($('.img_ctx img'),function(i,v){
				//获取包裹img的div
				var $img_parent= $(v).parent();
				//设置这个div的高度
				$img_parent.height($img_parent.width());
				//设置背景图为 当前的img
				$img_parent.css({backgroundImage:'url('+$(v).attr('src')+')'}) 
				
				//如果图片长宽一样 则设置宽度百分之百
				if($(v).width()==$(v).height()){
					$img_parent.css({backgroundSize:'100% 100%'}) 
				}
				
				//如果宽大于高 高度100%
				if($(v).width()>$(v).height()){
					//缩略百分比后的宽度
					var _width=$(v).width()*($img_parent.width()/$(v).height());
					$img_parent.css({backgroundSize: _width +'px 100%'}) 
				}else{//宽度 100%
					$img_parent.css({backgroundSize:'100%'}) 
				}
				
				//处理完图片后 把 img删掉,代表这个img已经处理过了
				$(v).remove();
			}) 
		})

猜你喜欢

转载自blog.csdn.net/m0_37992075/article/details/89601521
今日推荐