2016-04-08 19 views
0

我有下一个脚本。它在img加载之前有效,你使用方法加载。如何在加载img后强制脚本工作?

$(document).ready(function() { 
    $('.slide-img img').load(function(){ 
    var height = $(this).height(); 
    var width = $(this).width(); 
    if (width > height) { 
     $(this).attr('style', 'max-height: 100%'); 
    }; 
    if (height > width) { 
     $(this).attr('style', 'max-width: 100%'); 
    }; 
    }); 
}); 

我怎么能加载img后强制脚本工作?

+1

http://stackoverflow.com/questions/280049/javascript-当图像被加载时回调图像 –

+0

您可能想要查看某些图像预加载库以实现此目的。您的代码只能在DOM准备就绪时运行。 http://www.createjs.com/preloadjs可能会矫枉过正,但绝对是一种选择。 –

+0

你的代码看起来很好。检查您的选择器是否正确。 –

回答

0

使用window.load方法(jQuery的):

$(window).load(function() { 
// this will fire after the entire page is loaded, including images 
}); 

或者使用的window.onload方法(JavaScript的):

window.onload = function() { 
// this will fire after the entire page is loaded, including images 
}; 
+0

谢谢你的回答!但它不工作,或者我错了。 看这里请 - https://jsfiddle.net/kino45/jo82d6pw/1/ –

+0

你在jsfiddle中添加jQuery吗?检查我的codepen:http://codepen.io/anon/pen/RaxyGQ – Sumanta736

+0

不包括你的图像加载功能,$(窗口).load照顾你的图像加载。检查我的答案评论部分。 – Sumanta736

相关问题