Home > Article > Web Front-end > jQ handles images that are too large in the page_html/css_WEB-ITnose
This is a very practical function. It is inevitable that some oversized pictures will appear on the web page, which will stretch the page or partially hide the pictures. We usually use the max-width of CSS To control it, but ie6 doesn't like this. I encountered this kind of confusion when I was building a website. Because I was learning jQuery recently, I thought of using jq to deal with this problem. After some thinking, I feel that this problem is actually not difficult. Let’s explain it in detail below:
1. Idea:
To solve the size problem, we must first obtain The width and height of the picture, and then define a maximum width and make a judgment. If the actual width is greater than the set maximum width, then make the actual width equal to the maximum width, and the height can be reduced proportionally according to the aspect ratio. I organized my thoughts and listed the Chinese sentences:
1) Set the maximum width
2) Get the image width
3) Get the image height
4) Define the proportional relationship of the height ( New height = height/width * set width)
5) Determine, if width > set maximum width
6) then width = maximum width; height = new height
7) End
2. Code:
Write the above Chinese statement into a complete jQ statement:
$(function() {
$(' .content img').each(function() {
var maxWidth = 600;
var width = $(this).width();
var height = $(this).height();
var newHeight = height / width * maxWidth;
if(width > maxWidth) {
$(this).width(maxWidth);
$(this).height(newHeight);
}
});
});
The .content img here is the selector, which should be modified according to the actual web page structure, such as the following structure: