用jQuery在图片加载完成后改变图片大小

来源:互联网 发布:帝王三国单机无需网络 编辑:程序博客网 时间:2024/05/18 02:44

要改变图片的大小并不难,可以用jQuery操作css改变。但是前提是要判断图片是否加载完成。主要是通过jQuery的load事件和onreadystatechange来判断其状态。

对于IE6,用onreadystatechange可以直接处理,在IE7中,则需要用定时器来判断图片的readystate状态。而对于FF和Chrome刚可以直接用load事件来判断。

以下是在实例中使用的完整代码:

<script type="text/javascript">$(document).ready(function(){        function changeSize(obj){//本函数用于在图片加载时对图片大小等进行设置            w=obj.width();            h=obj.height();            t=obj.attr("title");            src=obj.attr("src");            obj.width(w>400?400:w);            obj.height(w>400?(400/w)*h:h);            obj.css("cursor","pointer");            obj.click(function(){                $("#picDlg").html("<img src="+src+" border=0/>").fadeIn(1000).dialog({                    width:"auto",                    height:"auto",                    title:t,                    modal:true,                    draggable:false,                    resizable:false                })            })        }          if($.browser.msie){            //IE 6.0            if($.browser.version==6.0){                $(".bodyLeft img").each(function(ind,ele){                   // ele.onreadystatechange =function(){                        if(ele.readyState == "complete"||ele.readyState=="loaded"){                            changeSize($(this));                        }                    //}                })            }            //IE 6.0以上            else{                $(".bodyLeft img").each(function(){                    tempTimer=window.setInterval(function(ind,ele){                        if(ele.readyState=="complete"){                            window.clearInterval(tempTimer);                            changeSize($(this));                        }                        else{                            return;                        }                    },200);                })            }          }        //FF,Chrome        else{            $(".bodyLeft img").each(function(ind,ele){                alert(ele.complete);                if(ele.complete==true){                    changeSize($(this));                }            })        }})</script>

上面的图片可以将图片等比例缩小显示在文章中,同时使用的jQuery的Dialog UI组件单击图片时,以一个层显示完整大小的图片。

原创粉丝点击