×

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

作者:Terry2017.02.05来源:Web前端之家浏览:8579评论:0
关键词:JQueryJS

核心代码:

$(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上都能实现控制图片显示时的最大宽度。

您的支持是我们创作的动力!
温馨提示:本文作者系Terry ,经Web前端之家编辑修改或补充,转载请注明出处和本文链接:
https://jiangweishan.com/article/svg1486224000505.html

网友评论文明上网理性发言 已有0人参与

发表评论: