教程集 www.jiaochengji.com
教程集 >  jQuery  >  jquery 教程  >  正文 JS自动缩小超出大小的图片

JS自动缩小超出大小的图片

发布时间:2013-09-29   编辑:jiaochengji.com
在文章的正文中,往往会出现一些超大的图片,把页面撑开变形,影响了美观。用这段JS代码就可解决这个问题,你可以把图片的最大值限定在一定范围内,当图片大小超出这个尺寸后,就会被自动按比例缩小
复制代码 代码如下:

<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
jQuery.fn.LoadImage=function(scaling,width,height,loadpic){
if(loadpic==null)loadpic="../img/loading.gif";
return this.each(function(){
var t=$(this);
var src=$(this).attr("src")
var img=new Image();
img.src=src;
//自动缩放图片
var autoScaling=function(){
if(scaling){
if(img.width>0 && img.height>0){
if(img.width/img.height>=width/height){
if(img.width>width){
t.width(width);
t.height((img.height*width)/img.width);
}else{
t.width(img.width);
t.height(img.height);
}
}
else{
if(img.height>height){
t.height(height);
t.width((img.width*height)/img.height);
}else{
t.width(img.width);
t.height(img.height);
}
}
}
}
}
//处理ff下会自动读取缓存图片
if(img.complete){
autoScaling();
return;
}
$(this).attr("src","");
var loading=$("<img alt=\"加载中...\" title=\"图片加载中...\" src=\""+loadpic+"\" />");
t.hide();
t.after(loading);
$(img).load(function(){
autoScaling();
loading.remove();
t.attr("src",this.src);
t.show();
});
} );
}
</script>
<div id="content"><img src="img/20120518073933709.jpg"/></div>
<script type="text/javascript">
<!--
$(window).load(function(){
$('#content img').LoadImage(true, 600,500,'img/loading.gif');
});
//-->
</script>

您可能感兴趣的文章:
JS自动缩小超出大小的图片
等比例缩小图片尺寸的js代码
解决dedecms内容页图片过大不显示或撑破表格
jQuery相册插件 AD Gallery
如何用CSS控制图片自适应大小?
js结合css实现图片自动等比例缩小且垂直居中的代码
jQuery动态改变图片显示大小(示例代码)
js等比例缩小图片尺寸的例子
jquery图片不完全按比例自动缩小的简单代码
移动端利用H5实现压缩图片上传的功能

关键词: 自动缩小   
[关闭]
~ ~