JS自动缩放页面图片

本文介绍如何使用JavaScript让页面中的图片根据浏览器窗口大小自动调整尺寸,适应不同设备显示。这种方法适合图片数量不多的场景。

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

注:该方法不适用于图片较多的页面!

/**
 * 缩略图
 *
 * @param bool isScaling 是否缩放
 * @param int width 宽度
 * @param int height 高度
 * @param string loadindPic 表示“正在加载中”的图片地址
 */
jQuery.fn.LoadImage = function (isScaling, width, height, loadindPic) {
	if (loadindPic == null) {
		loadindPic = "../images/msg_img/loading.gif";
	}

	return this.each(function () {
		var _this = $(this);
		var src = $(this).attr("src")
			var img = new Image();
		img.src = src;

		// 自动缩放图片
		var autoScaling = function () {
			if (isScaling) {
				if (img.width > 0 && img.height > 0) {
					if (img.width / img.height >= width / height) {
						if (img.width > width) {
							_this.width(width);
							_this.height((img.height * width) / img.width);
						} else {
							_this.width(img.width);
							_this.height(img.height);
						}
					} else {
						if (img.height > height) {
							_this.height(height);
							_this.width((img.width * height) / img.height);
						} else {
							_this.width(img.width);
							_this.height(img.height);
						}
					}
				}
			}
		}

		// 处理ff下会自动读取缓存图片
		if (img.complete) {
			autoScaling();
			return;
		}
		$(this).attr("src", "");
		var loading = $("<img alt=\"加载中...\" title=\"图片加载中...\" src=\"" + loadindPic + "\" />");

		_this.hide();
		_this.after(loading);
		$(img).load(function () {
			autoScaling();
			loading.remove();
			_this.attr("src", this.src);
			_this.show();
			//$('.photo_prev a,.photo_next a').height($('#big-pic img').height());
		});
	});
}


// 应用举例
$(function () {
	$('#Article .content img').LoadImage(true, 660, 660, 'http://127.0.0.12:8088/statics/images/s_nopic.gif');
})


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值