// 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');
// 獲取圖片頭尺寸數(shù)據(jù)后立即調(diào)整圖片
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);
/**
* 圖片頭數(shù)據(jù)加載就緒事件
* @see http://www.planeart.cn/?p=1121
* @param {String} 圖片路徑
* @param {Function} 尺寸就緒 (參數(shù)1接收width; 參數(shù)2接收height)
* @param {Function} 加載完畢 (可選. 參數(shù)1接收width; 參數(shù)2接收height)
* @param {Function} 加載錯誤 (可選)
*/
var imgReady = (function () {
var list = [], intervalId = null,
// 用來執(zhí)行隊列
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;
// 如果圖片被緩存,則直接返回緩存數(shù)據(jù)
if (img.complete) {
ready(img.width, img.height);
load && load(img.width, img.height);
return;
};
// 檢測圖片大小的改變
width = img.width;
height = img.height;
check = function () {
newWidth = img.width;
newHeight = img.height;
if (newWidth !== width || newHeight !== height ||
// 如果圖片已經(jīng)在其他地方加載可使用面積檢測
newWidth * newHeight > 1024
) {
ready(newWidth, newHeight);
check.end = true;
};
};
check();
// 加載錯誤后的事件
img.onerror = function () {
error && error();
check.end = true;
img = img.onload = img.onerror = null;
};
// 完全加載完畢的事件
img.onload = function () {
load && load(img.width, img.height);
!check.end && check();
// IE gif動畫會循環(huán)執(zhí)行onload,置空onload即可
img = img.onload = img.onerror = null;
};
// 加入隊列中定期執(zhí)行
if (!check.end) {
list.push(check);
// 無論何時只允許出現(xiàn)一個定時器,減少瀏覽器性能損耗
if (intervalId === null) intervalId = setInterval(tick, 40);
};
};
})();
})(jQuery);
本站僅提供存儲服務(wù),所有內(nèi)容均由用戶發(fā)布,如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請
點擊舉報。