本文實例講述了jQuery限制圖片大小的方法。分享給大家供大家參考,具體如下:
最近在搞一個信息網站,文章內容中可以顯示圖片,所以就需要限制用戶貼進去的圖片的顯示大小了。
在網上找到一段代碼:
$(document).ready(function(){  $("#viewnews_body img").each(function(){    var width = 620;    var height = 600;    var image = $(this);    if (image.width() > image.height()){      if(image.width()>width){        image.width(width);        image.height(width/image.width()*image.height());      }    }else{      if(image.height()>height){        image.height(height);        image.width(height/image.height()*image.width());      }    }  });});用這個方法了實現運行效果不穩定,有時間圖片還沒有加載完畢就會先執行了。
所以改用給所有需要限制大小的圖片綁定load事件的方法來實現,這樣保證了在每個圖片加載完后再分別執行限制大小的代碼。代碼如下:
$(document).ready(function(){  $("#viewnews_body img").bind("load",function(){    var width = 620;    var height = 600;    var image = $(this);    if (image.width() > image.height()){      if(image.width()>width){        image.width(width);        image.height(width/image.width()*image.height());      }    }else{      if(image.height()>height){        image.height(height);        image.width(height/image.height()*image.width());      }    }  });});更多關于jQuery相關內容感興趣的讀者可查看本站專題:《jquery中Ajax用法總結》、《jQuery表格(table)操作技巧匯總》、《jQuery拖拽特效與技巧總結》、《jQuery擴展技巧總結》、《jQuery常見經典特效匯總》、《jQuery動畫與特效用法總結》、《jquery選擇器用法總結》及《jQuery常用插件及用法總結》
希望本文所述對大家jQuery程序設計有所幫助。
新聞熱點
疑難解答