Jquery and other proportion control image width and height of the concrete implementation

  • 2020-03-30 01:29:48
  • OfStack

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"," Click to see the original image "); 
$(this).click(function(){window.open($(this).attr("src"))}); 
} 
}); 
}); 

If the above code cannot be executed, the following code can be used:


$(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"," Click to see the original image "); 
	$(this).click(function(){window.open($(this).attr("src"))}); 
	} 
	}); 
});

There is also a way through CSS compatibility with IE6 that allows images to automatically scale down when they exceed a specified width, but this does not conform to 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 make it as compatible as possible with Internet explorer and other browsers as well as W3C standards through js to control the width of the image, the following use jquery to control the maximum width of the image display, 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, just cate style so the maximum width of img is only 600px. .each (function () {... }), each in this case is the method called one by one on the specified image collection object. This jquery method controls the maximum width of images displayed in IE6 and above browsers and in chrome and Firefox.


Related articles: