图片在页面显示的处理方法

var w=$(".img li i").width();  //获取图片承载容器的宽度
$(".img li i").height(w*0.618); //设置图片承载容器的高度

$(window).resize(function(){ //浏览器窗口大小改变时重新获取图片承载容器的宽度、设置其高度
  var w=$(".img li i").width();
  $(".img li i").height(w*0.618);
});

function
img() { var a=$(this).width(), //获取图片宽度 b=$(this).height(), //获取图片高度 e=a/b; //计算宽高比 if(a>=b){ //如果宽度大于高度 if(e<1.618){ //如果宽高比小于等于1.618【PS.黄金比例宽高比1.618(宽1.618、高1)和0.618(宽0.618、高1)】,高度超出 $(this).css({"100%",height:"auto"}); //使宽度100%,保证宽度不留空白边 /*图片居中*/ var imgH = $(this).height(), //获取此时对应的图片高度 iH = $(this).parent().height(), //获取其承载元素的高度 h = -(imgH - iH)/2; //img-iH为图片高度超出承载容器的部分的高度 $(this).css('marginTop',h) //设置图片在容器中垂直居中 }else{ //如果宽高比大于1.618,宽度超出 $(this).css({height:"100%","auto"}); //使高度100%显示,保证高度不留空白边 /*图片居中*/ var imgW = $(this).width(), //获取此时对应的图片宽度 iW = $(this).parent().width(), //获取其承载元素的宽度 w = -(imgW - iW)/2; //imgW-iW为图片宽度超出承载容器的部分的宽度 $(this).css('marginLeft',w) //设置图片在容器中水平居中 } }else{ //高度大于宽度(代码同宽高比e小于1.618) $(this).css({"100%",height:"auto"}); /*图片居中*/ var imgH = $(this).height(), iH = $(this).parent().height(), h = -(imgH - iH)/2; $(this).css('marginTop',h) } }
原文地址:https://www.cnblogs.com/vscss/p/5742652.html