Home  >  Article  >  Web Front-end  >  The specific implementation of using jquery to control the width and height of images in equal proportions_jquery

The specific implementation of using jquery to control the width and height of images in equal proportions_jquery

WBOY
WBOYOriginal
2016-05-16 17:01:46960browse

Core code:

$(function() { 
$(".dvcontent img").each(function() { 
var maxwidth = 520; 
if ($(this).width() > maxwidth) { 
var oldwidth = $(this).width(); 
var oldheight = $(this).height(); 
var newheight = maxwidth/oldwidth*oldheight; 
$(this).css({width:maxwidth+"px",height:newheight+"px",cursor:"pointer"}); 
$(this).attr("title","点击查看原图"); 
$(this).click(function(){window.open($(this).attr("src"))}); 
} 
}); 
}); 

If the above code cannot be executed, you can use the following code:

$(window).load(function() {
	$(".dvcontent img").each(function() { 
	var maxwidth = 600; 
	if ($(this).width() > maxwidth) { 
	var oldwidth = $(this).width(); 
	var oldheight = $(this).height(); 
	var newheight = maxwidth/oldwidth*oldheight; 
	$(this).css({width:maxwidth+"px",height:newheight+"px",cursor:"pointer"}); 
	$(this).attr("title","点击查看原图"); 
	$(this).click(function(){window.open($(this).attr("src"))}); 
	} 
	}); 
});

There is also a method through CSS that is compatible with IE6 and allows the image to be automatically scaled down when it exceeds the specified width, but this writing method does not comply with W3C standards. The code is as follows:

.cate img{
    max-width: 600px; 
    height:auto; 
    width:expression(this.width > 600 ? "600px" : this.width);
 }

So in order to be as compatible as possible with IE and other browsers and in compliance with W3C standards, we use js to control the width of the image. Below, we use jquery to control the maximum width of the image when it is displayed. The main code is as follows:

$(window).load(function() {
    $(".cate img").each(function() {
        var maxwidth = 600;
        if ($(this).width() > maxwidth) {
            $(this).width(maxwidth);
        }
    });
});

The code is very simple, it is in cate style, so the maximum width of img can only be 600px. .each(function(){......}), where each calls the following methods one by one on the specified image collection object. This jquery method can control the maximum width of image display in IE6 and above browsers, chrome and Firefox.

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