1、新建html文档。
2、准备好需要用到的图片。这里只截图因为图片,推荐3张图片做测试,第一张宽度1000px高度300px,第二张宽度400px高度2000px,第三张宽度3000px高度3000px。图片只做测试用
3、书写hmtl代码。<div class="list clear"> <ul> <li><a href="#" class="list_img"><img src="aa.png"/></a></li> <li><a href="#" class="list_img"><img src="bb.png"/></a></li> <li><a href="#" class="list_img"><img src="cc.jpg"/></a></li> </ul></div>
4、初始化css代码。<style>@charset "utf-8";/* CSS Document */body { margin:0; padding:0;font-size:14px;font-family:'\5FAE\8F6F\96C5\9ED1',Arial, Helvetica, sans-serif;-webkit-font-smoothing:antialiased;-webkit-text-size-adjust:100%;background-attachment: fixed; /* prevent screen flash in IE6 \5b8b\4f53 宋体 */ background:#FFF;}div,form,img,ul,ol,li,p,dl,dt,dd { margin: 0; padding: 0; border: 0;}h1,h2,h3,h4,h5,h6 { margin:0; padding:0;font-family:'\5FAE\8F6F\96C5\9ED1';font-weight:normal;font-size:14px;}address, caption, cite, code, dfn, th, var { font-style: normal; font-weight: normal;}fieldset, img, input { border: 0 none;outline:none;}table{border-collapse: collapse; border-spacing: 0;}ul,li {list-style:none;}i,em{ font-style:normal;}fieldset,img{border:0px;}textarea { resize: vertical }a {text-decoration:none; color:#333; blr:exPRession(this.onFocus=this.blur());-webkit-transition: all 0.3s ease; -moz-transition: all 0.3s ease; -o-transition: all 0.3s ease; transition: all 0.3s ease;}a:focus { outline:0;}a:hover{text-decoration:none; color:#c20e1a;-webkit-transition: all 0.3s ease; -moz-transition: all 0.3s ease; -o-transition: all 0.3s ease; transition: all 0.3s ease;}a:active { color:red;}.clear:after,ul:after{content:"";display:block;visibility:hidden;height:0;clear:both;}.clear,.area,.con:after{zoom:1}.news_list ul li:before{ content:"·";}.left { float: left;}.right { float: right;}</style>
5、书写css代码。<style>.list{ padding:10px;}.list ul li{ width:49%; float:left; margin-bottom:10px;}.list ul li:nth-child(2n-1){ padding-right:1%;}.list ul li:nth-child(2n){ padding-left:1%;}.list ul li a{ display:block;overflow:hidden; background:#f1f1f1;}.list ul li a img{ display:block; margin:0 auto;}</style>
6、书写并添加js代码。<script src="jquery-1.11.1.min.js"></script><script> $(document).ready(function(){ $("img").on("load",function(){ //图片加载完成之后实际尺寸 $(".list_img").css("width",($(".list_img").width())); $(".list_img").css("height",($(".list_img").width())); var img_w = $(this).width(); var img_h = $(this).height(); if (img_w<img_h) { $(this).parents('.list_img').find("img").css("height",($(".list_img").width())); } else if (img_w>img_h) { $(this).parents('.list_img').find("img").css("width",($(".list_img").width())); $(this).parents('.list_img').find("img").css("margin-top",((($(".list_img").height())-($(this).height()))/2+"px")); } else { $(this).parents('.list_img').find("img").css("width",($(".list_img").width())); $(this).parents('.list_img').find("img").css("height",($(".list_img").width())); } }); });</script>
7、代码整体结构。
8、查看效果。最终测试效果是用的浏览器的手机模式测试的。