JQuery to achieve the scale of large images so that large images adaptive page layout

  • 2020-03-26 21:30:35
  • OfStack

When layout a page, it is sometimes possible to encounter large images that "burst" the page container, especially when loading an outer link image (usually through a collection of images from an outer site). This article will show you how to scale large images using jQuery to make large images adaptive to page layout.

Usually we handle thumbnails by using background code (PHP,.net, Java, etc.) to generate a certain size of thumbnails according to the large image, for the foreground page call, of course, there is also the use of foreground javascript script will be loaded after the large image forced to scale, into the so-called thumbnails, this method is not desirable. However, for the website content page, such as the article details page, if you need to load a large picture, in order to prevent "bursting" the layout, we use jQuery to scale the picture. Let's talk about it in two ways:

1. Know the size of the picture
 
<div id="demo1"> 
<img src="a.jpg" width="800" height="300" alt=" The picture "> 
</div> 

When the image loaded by the page contains the attributes width and height, you can use a few simple jQuery lines to achieve equal scaling.
 
$(function(){ 
var w = $("#demo1").width();//Width of the container
$("#demo1 img").each(function(){//If we have many images, we can iterate through each()
var img_w = $(this).width();//Image width
var img_h = $(this).height();//Picture height
if(img_w>w){//If the picture is wider than the container - burst
var height = (w*img_h)/img_w; //Height isometric scaling
$(this).css({"width":w,"height":height});//Set the zoomed width and height
} 
}); 
}); 

2. Unknown picture size

When the size of the image loaded on the page is unknown, the above code can not be effectively scaled, which often occurs in the collection of external link images.
 
<div id="demo2"> 
<img src="a.jpg" alt=" The picture "> 
</div> 

Fortunately, some well-meaning friends have written special plug-ins to handle this, and cross-browser, to solve the front-end friends of a big problem.

The following is a grand introduction to autoIMG.

AutoIMG can quickly adapt the size of the article image, it USES the browser to obtain the size of the image file header data, without waiting for the image to load.

AutoIMG compatibility: Chrome | Firefox | Sifari | Opera | IE6 | IE7 | IE8 |...

Calling the autoIMG plug-in method is fairly simple:
 
$(function(){ 
$("#demo2").autoIMG(); 
}); 

(link: http://xiazai.jb51.net/201310/yuanma/autoIMG_jb51.net.rar)

Related articles: