When laying out a page, sometimes you will encounter a situation where large pictures "break" the page container, especially when loading external link pictures (usually collected pictures from external sites). So this article will tell you how to use jQuery to scale large pictures proportionally and make them adapt to the page layout.
Usually when we process thumbnails, we use back-end code (PHP, .net, Java, etc.) to generate thumbnails of a certain size based on large pictures for the front-end page to call. Of course, we also use front-end javascript scripts to load the thumbnails. It is not advisable to force a large image to be zoomed into a so-called thumbnail. However, for website content pages, such as the article details page of this website, if a large image needs to be loaded, in order to prevent "breaking" the layout, we use jQuery to scale the image proportionally. We will talk about it in two situations:
1. Known image size
When the image loaded on the page contains attribute width and height values, you can use a few simple jQuery codes to achieve equal scaling.
$(function(){
var w = $("#demo1").width();//Container width
$("#demo1 img").each(function(){//If there are many pictures, we can use each() to traverse
var img_w = $(this).width();//Picture width
var img_h = $(this).height();//Picture height
if(img_w>w){//If picture The width exceeds the width of the container - it will burst
var height = (w*img_h)/img_w; //Height scaling
$(this).css({"width":w,"height" :height});//Set the width and height after scaling
}
});
});
2. Unknown image size
When the size of the image loaded on the page is unknown, the above code cannot be effectively scaled. This situation often occurs in the collected external link images.
Fortunately, some kind friends have written a special plug-in to handle it. , and it is cross-browser, solving a major problem for front-end friends.
The following is a grand introduction to autoIMG.
autoIMG can quickly adapt the size of article images. It uses the browser to obtain image file header size data without waiting for the image to be loaded.
autoIMG is compatible with: Chrome | Firefox | Sifari | Opera | IE6 | IE7 | IE8 | ...
The method of calling the autoIMG plug-in is quite simple:
$(function(){
$("#demo2").autoIMG();
});
autoIMG instance download