JS自动缩小超出大小的图片
更新时间:2012年10月12日 18:03:20 作者:
在文章的正文中,往往会出现一些超大的图片,把页面撑开变形,影响了美观。用这段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>
相关文章
jQuery progressbar通过Ajax请求实现后台进度实时功能
这篇文章主要介绍了jQuery progressbar通过Ajax请求实现后台进度实时功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下2016-10-10
jQuery实现点击自身以外区域关闭弹出层功能完整示例【改进版】
这篇文章主要介绍了jQuery实现点击自身以外区域关闭弹出层功能,结合具体实例形式分析了jQuery事件响应及页面元素属性动态操作实现弹出层打开与关闭相关操作技巧,需要的朋友可以参考下2018-07-07


最新评论