Posted 2015-11-25Updated 2016-07-222 minutes read (About 337 words) visitsjs按比例缩放图片并显示图片的一部分1234567891011121314151617181920212223242526272829303132333435363738394041424344454647$(document).ready(function(){ //取得图片外层div的宽度 var boxwidth = $(‘.media-object’).parent().width(); var boxheight = boxwidth*9/16; var imgarray = $(‘.media-object’); for(var i=0;i<imgarray.length;i++){ //获取图片原始长、宽 var width = imgarray[i].width ; var height = imgarray[i].height; //判断图片长宽比例 if( width*9/16 > boxheight ){ //使用宽度按16:9的比例缩放后高度不够,转而使用高度 //此时图片高度应该设为div高 boxheight var imgheight = boxheight; $(imgarray[i]).css(‘height’,imgheight); //此高度下等比例的图片宽度为 imgwidth var imgwidth = imgheight*width/height; $(imgarray[i]).css(‘width’,imgwidth); //计算此时图片宽度与div宽度的差值 var difference = imgwidth-boxwidth; //计算图片应该裁剪的位置 var stratX = difference/2; var startY = 0; var endX = imgwidth – difference/2; var endY = imgheight; //使用css clip:rect(top, right, bottom, left)属性裁剪 $(imgarray[i]).css(‘clip’,’rect(‘+stratX+’px ‘+endX+’px ‘+endY+’px ‘+startY+’px)’); }else{ //使用宽度按照16:9缩放,多余的高度去除 //此时图片宽度应该设为div宽 boxwidth var imgwidth = boxwidth; $(imgarray[i]).css(‘width’,imgwidth); //此宽度下等比例的图片高度为 imgheight var imgheight = imgwidth*height/width; $(imgarray[i]).css(‘height’,imgheight); //计算此时图片高度与div高度的差值 var difference = imgheight-boxheight; //计算图片应该裁剪的位置 var stratX = 0; var startY = difference/2; var endX = imgwidth; var endY = imgheight – difference/2; //使用css clip:rect(top, right, bottom, left)属性裁剪 $(imgarray[i]).css(‘clip’,’rect(‘+stratX+’px ‘+endX+’px ‘+endY+’px ‘+startY+’px)’); } } }); js按比例缩放图片并显示图片的一部分https://ldsun.com/2015/11/25/js按比例缩放图片并显示图片的一部分/AuthorLudisPosted on2015-11-25Updated on2016-07-22Licensed under