2017-03-17 103 views
0

我添加了jQuery函數來調整大小圖片的大小以適合div(200px 200px並且不確定該函數是否正確),但是每次刷新頁面時函數都會執行再次和圖片出現在整個屏幕上一秒鐘!我怎樣才能防止這個?我的功能:JQuery圖片大小調整出現在整個屏幕上

$(document).ready(function() { 
    $('.profile-picture img').each(function() { 

     var width = $(this).width(); 
     var height = $(this).height(); 

     if(width > height) { 
      $(this).css("max-width", "100%"); 
      $(this).css("height", "100%"); 
     }else { 
      $(this).css("width", "100%"); 
      $(this).css("max-height", "100%"); 
     } 
    }); 
}); 

在一個後我發現答案是在說:「你有回調做」,但不知道怎麼辦。你能給我建議嗎?先謝謝你!

+1

它這樣做是因爲該頁面不呈現,直到你的'$(文件).ready'(準備好)。防止這種情況的最好方法是通過AJAX加載圖片。 – Sablefoste

回答

0

在頁面被瀏覽器渲染後,觸發.ready()事件。爲了防止你描述的問題,你應該在CSS中設置一些默認值。

更進一步,您可以在CSS中設置所有樣式,然後僅使用Javascript中的類進行操作。

CSS:

.profile-picture { 
    width: 200px; 
    height: 200px; 
} 
.profile-picture img { 
    width: 100%; 
    max-height: 100%; 
} 
.profile-picture img.tall { 
    max-width: 100%; 
    height: 100%; 
} 

的Javascript:

$(document).ready(function() { 
    $('.profile-picture img').each(function() { 
    if($(this).width() < $(this).height()) { 
     $(this).addClass('tall'); 
    } 
    }); 
}); 
+0

非常感謝! –