2017-03-17 101 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

非常感谢! –