Home  >  Article  >  Web Front-end  >  autoIMG image adaptive plug-in code based on jquery_jquery

autoIMG image adaptive plug-in code based on jquery_jquery

WBOY
WBOYOriginal
2016-05-16 18:09:351490browse

In order to prevent the image from breaking the layout, the most common method is to obtain the image size after onload and then adjust it, so it will still break during the loading process. The picture of Qzone log has been improved here, and the original picture will be displayed after onload is completed. I have written a small example using onload before: http://www.planeart.cn/?p=1022
Using imgReady, you can achieve cross-browser image adaptation in dom ready without waiting for img to load. The code is as follows :

Copy code The code is as follows:

// jQuery.autoIMG.js v0.2
// Tang Bin - http://planeArt.cn/ - MIT Licensed
(function ($) {
var // Set the replacement image for loading status
tempPath = './images/loading.png',
// Set the replacement image for loading error
errorPath = './images/error.png',
// Check whether the css2.1 max-width attribute is supported
isMaxWidth = 'maxWidth' in document.documentElement.style,
// Check whether the IE7 browser is supported
isIE7 = !-[1,] && ! ('prototype' in Image) && isMaxWidth;
new Image().src = tempPath;
$.fn.autoIMG = function () {
var $this = this,
// Get Container width
maxWidth = $this.width();
return $this.find('img').each(function (i, img) {
// Use if max-width attribute is supported Otherwise, use the following preloading method
if (isMaxWidth) return img.style.maxWidth = maxWidth 'px';
var path = img.getAttribute('data-src') || img.src,
next = img.nextSibling,
parent = img.parentNode,
temp = new Image();
// Delete the img image and replace it with the loading image
img.style.display = 'none';
img.removeAttribute('src');
img.parentNode.removeChild(img);
temp.src = tempPath;
next ? next.insertBefore(temp) : parent .appendChild(temp);
// Image size is ready for execution
imgReady(path, function (width, height) {
if (width > maxWidth) {
// Scaled proportionally
height = maxWidth / width * height,
width = maxWidth;
//Delete the loading image
temp.parentNode.removeChild(temp);
//Restore the adjusted original image
img.style.display = '';
img.style.width = width 'px';
img.style.height = height 'px';
img.setAttribute('src', path );
next ? next.insertBefore(img) : parent.appendChild(img);
};
}, function () {
// Loading error
temp.src = errorPath ;
temp.title = 'Image load error!';
});
});
};
// IE7 zoom image will be distorted, use private attributes to solve it through cubic interpolation
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);
// Get the size data of the image header
// http://www.planeart.cn/?p=1121
// @param {String} image path
// @param {Function} callback function to get the size (parameter 1 receives width ; Parameter 2 receives height)
// @param {Function} Loading error callback function (optional)
var imgReady = function (url, callback, error) {
var width, height, offsetWidth, offsetHeight, intervalId, check, div,
accuracy = 1024,
doc = document,
container = doc.body || doc.getElementsByTagName('head')[0],
img = new Image();
img.src = url;
// If the image is cached, return the cached data directly
if (img.complete) {
return callback(img.width, img. height);
};
// Insert a secret image into the page and monitor the image size ready status
if (container) {
div = doc.createElement('div');
div .style.cssText = 'visibility:hidden;position:absolute;left:0;top:0;width:1px;height:1px;overflow:hidden';
div.appendChild(img)
container.appendChild (div);
width = img.offsetWidth;
height = img.offsetHeight;
check = function () {
offsetWidth = img.offsetWidth;
offsetHeight = img.offsetHeight;
// If the image size starts to change, it means that the browser has obtained the image header data and occupied it
// After actual testing, only monitoring img.offsetWidth is effective, and detecting img.offsetHeight is for insurance
/ / If the area of ​​the newly inserted image is larger than the preset size, it is likely that the image is being loaded elsewhere before execution, such as a webkit-based browser
if (offsetWidth !== width || offsetHeight !== height || offsetWidth * offsetHeight > accuracy) {
clearInterval(intervalId);
callback(offsetWidth, offsetHeight);
// Clear img events and elements to avoid IE memory leaks
img.onload = null ;
div.innerHTML = '';
div.parentNode.removeChild(div);
};
};
check();
// Perform detection regularly
intervalId = setInterval(check, 150);
};
// Wait for the image to be completely loaded
// This is an insurance operation, if the above size monitoring method fails, this will be enabled
// If the loading time of a very small image is likely to be less than the detection interval defined by the timer, the timer will be stopped
img.onload = function () {
callback(img.width, img.height);
img.onload = img.onerror = null;
clearInterval(intervalId);
container && img.parentNode.removeChild(img);
};
// Image loading error
img.onerror = function () {
error && error();
clearInterval(intervalId);
container && img.parentNode.removeChild(img);
};
};
})(jQuery);

autoIMG compressed: 1.74kb, compatible with: Chrome | Firefox | Sifari | Opera | IE6 | IE7 | IE8 | …
Call the demo: $('#demo p').autoIMG()
Similarly, The delightful DEMO address is here: http://demo.jb51.net/js/2011/autoimg/
Postscript: Although I have the foreshadowing of imgReady technology in the previous article, I thought It would be very simple to implement this image adaptive plug-in, but in the process, I encountered a problem with the webkit-based browser. Later I learned that webkit had a bug that had not been fixed. After a long time, I updated the imgReady function.
Package download address
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn