基于jquery的防止大图片撑破页面的实现代码(立即缩放)

2020-05-23 06:18:58易采站长站整理

为了防止图片撑破布局,最常见的仍然是通过onload后获取图片尺寸再进行调整,所以加载过程中仍然会撑破。而Qzone日志的图片在此进行了改进,onload完毕后才显示原图。我以前用onload写过一个小例子:http://www.planeart.cn/?p=1022
通过imgReady可以跨浏览器在dom ready就可以实现图片自适应,无需等待img加载,代码如下:
(3-17修复网友crossyou 指出的一处错误,并且新版本去掉了替换图片)

// jquery.autoIMG.js – 2010-04-02 – Tang Bin – http://planeArt.cn/ – MIT Licensed
(function ($) {
// 检测是否支持css2.1 max-width属性
var isMaxWidth = ‘maxWidth’ in document.documentElement.style,
// 检测是否IE7浏览器
isIE7 = !-[1,] && !(‘prototype’ in Image) && isMaxWidth;
$.fn.autoIMG = function () {
var maxWidth = this.width();
return this.find(‘img’).each(function (i, img) {
// 如果支持max-width属性则使用此,否则使用下面方式
if (isMaxWidth) return img.style.maxWidth = maxWidth + ‘px’;
var src = img.src;
// 隐藏原图
img.style.display = ‘none’;
img.removeAttribute(‘src’);
// 获取图片头尺寸数据后立即调整图片
imgReady(src, function (width, height) {
// 等比例缩小
if (width > maxWidth) {
height = maxWidth / width * height,
width = maxWidth;
img.style.width = width + ‘px’;
img.style.height = height + ‘px’;
};
// 显示原图
img.style.display = ”;
img.setAttribute(‘src’, src);
});
});
};
// IE7缩放图片会失真,采用私有属性通过三次插值解决
isIE7 && (function (c,d,s) {s=d.createElement(‘style’);d.getElementsByTagName(‘head’)[0].appendChild(s);s.styleSheet&&(s.styleSheet.cssText+=c)||s.appendChild(d.createTextNode(c))})(‘img {-ms-interpolation-mode:bicubic}’,document);
/**
* 图片头数据加载就绪事件
* @see http://www.planeart.cn/?p=1121
* @param {String} 图片路径
* @param {Function} 尺寸就绪 (参数1接收width; 参数2接收height)
* @param {Function} 加载完毕 (可选. 参数1接收width; 参数2接收height)
* @param {Function} 加载错误 (可选)
*/
var imgReady = (function () {
var list = [], intervalId = null,
// 用来执行队列
tick = function () {
var i = 0;
for (; i < list.length; i++) {
list[i].end ? list.splice(i–, 1) : list[i]();
};
!list.length && stop();
},
// 停止所有定时器队列
stop = function () {
clearInterval(intervalId);
intervalId = null;
};
return function (url, ready, load, error) {
var check, width, height, newWidth, newHeight,
img = new Image();
img.src = url;
// 如果图片被缓存,则直接返回缓存数据