js控制图片在规定范围内以长宽比例自适应显示

本文介绍了一种使用JavaScript实现的图片自适应布局方法,确保图片能在不同尺寸的显示区域中保持原有比例显示,并实现了居中效果。代码适用于前端开发场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当图片在页面显示时,如果宽度大于高度且大于显示区域宽度那么以宽度为准等比缩放;如果高度大于宽度且大于显示区域高度那么以高度为准;若大者都小于显示区域对应尺寸时,不用缩放只用居中显示;要实现这个功能的话可以上传的时候用程序对图片裁切,而这里要将的是用js在web端实现此功能,其实很简单,js代码如下:

// JavaScript Document
function changeImgSize(target){
	//外框宽
	maxWidth = parseInt($(target).parent().css("width").replace(/px/,""));
	//外框高
	maxHeight = parseInt($(target).parent().css("height").replace(/px/,""));
	//图片宽
	imgWidth = target.offsetWidth;
	//图片高
	imgHeight = target.offsetHeight;
	
	
	var viewWidth,viewHeight;
	
	if (imgWidth / maxWidth > imgHeight / maxHeight){
		if (imgWidth > maxWidth){
			viewWidth = maxWidth;
			viewHeight = maxWidth / imgWidth * imgHeight;
			$(target).css("margin-top",(maxHeight - viewHeight) / 2);
		}else{
		    viewWidth = imgWidth;
			viewHeight = imgHeight;
			$(target).css("margin-top",(maxHeight - viewHeight) / 2);
			$(target).css("margin-left",(maxWidth - viewWidth) / 2);
		}
	}else if (imgWidth / maxWidth < imgHeight / maxHeight){
		if (imgHeight > maxHeight){
			viewHeight = maxHeight;
			viewWidth = maxHeight / imgHeight * imgWidth;
			$(target).css("margin-left",(maxWidth - viewWidth) / 2);
		}else{
		    viewWidth = imgWidth;
			viewHeight = imgHeight;
			$(target).css("margin-top",(maxHeight - viewHeight) / 2);
			$(target).css("margin-left",(maxWidth - viewWidth) / 2);
		}
		
	}
	$(target).css("width",viewWidth);
	$(target).css("height",viewHeight);
}


(function($) {
    $.fn.extend({
        reSize: function() {
			return this.each(function () {
                changeImgSize(this);
            });
        }
     });
})(jQuery);

 页面图片显示代码如下:

 

<div class="imgdiv"><img src="images/index_b.jpg" ></div>

 对应的样式如下:

.piclist .imgdiv {
width: 122px;
height: 92px;
float: left;
overflow: hidden;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值