jQuery實現(xiàn)圖片加載完成后改變圖片大小的方法

字號:


    本文實例講述了jQuery實現(xiàn)圖片加載完成后改變圖片大小的方法。分享給大家供大家參考,具體如下:
    要改變圖片的大小并不難,可以用jQuery操作css改變。但是前提是要判斷圖片是否加載完成。主要是通過jQuery的load事件和onreadystatechange來判斷其狀態(tài)。
    對于IE6,用onreadystatechange可以直接處理,在IE7中,則需要用定時器來判斷圖片的readystate狀態(tài)。而對于FF和Chrome剛可以直接用load事件來判斷。
    以下是在實例中使用的完整代碼:
    <script type="text/javascript">
    $(document).ready(function(){
      function changeSize(obj){
      //本函數(shù)用于在圖片加載時對圖片大小等進(jìn)行設(shè)置
       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組件單擊圖片時,以一個層顯示完整大小的圖片。
    希望本文所述對大家jQuery程序設(shè)計有所幫助。