CSS/Jquery解决图片预加载,未知高度垂直居中,等比例缩放

0 分享

官方客服

官方客服 2015-04-09 17:55:25

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title></title>
<style>
.box li{
    border:1px #ccc solid;
    list-style:none;
    padding:2px;
    width:200px;
    height:200px;
    overflow:hidden;
    text-align:center;
    display:table-cell;
    vertical-align:middle;
    *display:block;
}
.box li img{vertical-align:middle;}
</style>
</head>
<body>
<ul class="box">
    <li><img src="000.jpg"></li>
    <li><img src="111.jpg"></li>
    <li><img src="222.jpg"></li>
</ul>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
//可另存JS调用
jQuery.fn.LoadImage=function(scaling,width,height,loadpic){
    if(loadpic==null)loadpic="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);
                        }
                    }
                }
            }   
        }
        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>
<script language="javascript">
$(".box li img").LoadImage(true,200,200);//调用方法,这里是关键
</script>
</body>
</html>



本帖已关闭回复或无回复权限!

本周热贴