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>
<p id="content"><img src="img/20120518073933709.jpg"/></p>
<script type="text/javascript">
<!–
$(window).load(function(){
$('#content img').LoadImage(true, 600,500,'img/loading.gif');
});
//–>
</script>

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *