Heim  >  Artikel  >  Web-Frontend  >  用jquery等比例控制图片宽高的具体实现_jquery

用jquery等比例控制图片宽高的具体实现_jquery

WBOY
WBOYOriginal
2016-05-16 17:01:46959Durchsuche

核心代码:

$(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"))}); 
} 
}); 
}); 

如果上面的代码不能执行,可以使用下面的代码:

$(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"))}); 
	} 
	}); 
});

通过css还有一种方法兼容IE6能让图片在超过规定的宽度时自动按比例缩小,但该写法不符合W3C标准。代码如下:

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

所以在做到尽量兼容IE和其他浏览器以及符合W3C的标准下就通过js来控制图片的宽度了,下面使用jquery控制图片显示时的最大宽度,主代码如下:

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

代码很简单,就是cate样式下的所以img的最大宽度只能为600px。.each(function(){......}),each在这里是对指定的图片集合对象逐一调用下面的方法。这种jquery方法在IE6及以上浏览器和chrome及Firefox上都能实现控制图片显示时的最大宽度。

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn