jquery操作html中圖片寬高自適應


在網站制作中如果后台上傳的圖片不做寬高限制,在前台顯示的時候,經常會出現圖片變形,實用下面方法可以讓圖片根據寬高自適應,不論是長圖片或者高圖片都可以完美顯示。

$("#myTab0_Content0 img").each(function(i){
var img = $(this);
var realWidth;//真實的寬度
var realHeight;//真實的高度
//這里做下說明,$("<img/>")這里是創建一個臨時的img標簽,類似js創建一個new Image()對象!
$("<img/>").attr("src", $(img).attr("src")).load(function() {

// 后台上傳圖片的真實寬高(像素)
realWidth = this.width;
realHeight = this.height;
//alert(realWidth)
//alert(realHeight)
// 樣式定義的li的寬
var imgWcss = $('.mp5List li').width();
//alert(imgWcss);
// 標准的圖片比例
var imgBz = 294/220;

// li高
var h = imgWcss/imgBz;
$('.mp5List li').css('height',h+'px');


//圖片太高,高自動,寬固定
if( realWidth < realHeight){
$(img).css({'width':imgWcss+ 'px','height':'auto' });
// alert(imgWcss)
//alert(1);

}
//圖片太寬,寬自動,高固定
if( realWidth > realHeight){
$(img).css({'height':h+'px', 'width':'auto' });


}
})
})


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM